pdf转换
namespace Utilities
{
public static class PDFHelper
{ /// <summary>
/// Html转Pdf
/// </summary>
/// <param name="strHtmlData">HTML内容</param>
/// <param name="filePath">文件路径</param>
/// <param name="fileName">文件名</param>
public static bool HtmlToPdfByInfo(string strHtmlData, string filePath, string fileName)
{
FileStream fs = null;
try
{
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
//获得字节数组
byte[] bPDF = ConvertHtmlTextToPDF(strHtmlData); if (bPDF == null)
{
return false;
} fs = new FileStream(Path.Combine(filePath, fileName), FileMode.Create); //开始写入
fs.Write(bPDF, , bPDF.Length);
return true;
}
catch (Exception)
{
throw;
}
finally
{
//清空缓冲区、关闭流
if (fs != null)
{
fs.Flush();
fs.Close();
}
}
} public static bool DownLoadFile(string url, string filePath, string fileName)
{
try
{
WebClient wc = new WebClient();
wc.Encoding = System.Text.Encoding.UTF8;
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
wc.DownloadFile(url, Path.Combine(filePath, fileName)); return true;
}
catch (Exception ex)
{
string strLog = string.Format("下载文件名:{0};文件下载地址:{1};错误信息:{2}。", fileName, url, ex.StackTrace);
LogHelper.Info(strLog);
throw ex;
} } #region HTML模板方式转PDF(格式问题)
/// <summary>
/// Html转Pdf
/// </summary>
/// <param name="url">页面地址,要完整地址</param>
/// <param name="filePath">文件路径</param>
/// <param name="fileName">文件名</param>
public static bool HtmlToPdf(string url, string filePath, string fileName)
{
FileStream fs = null;
try
{
WebClient wc = new WebClient();
wc.Encoding = System.Text.Encoding.UTF8;
//从网址下载Html字串
string htmlText = wc.DownloadString(url); //StreamWriter TxtWriter = new StreamWriter(@"D:\logfile.txt", true);
//TxtWriter.Write("0" + Environment.NewLine);
//TxtWriter.Write(htmlText + Environment.NewLine);
//TxtWriter.Close(); //获得字节数组
byte[] bPDF = ConvertHtmlTextToPDF(htmlText); if (bPDF == null)
{
return false;
} if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
fs = new FileStream(Path.Combine(filePath, fileName), FileMode.Create); //开始写入
fs.Write(bPDF, , bPDF.Length); return true;
}
catch (Exception ex)
{
string strLog = string.Format("HTML模板方式转PDF 文件名:{0};文件下载地址:{1};错误信息:{2}。", fileName, url, ex.StackTrace);
LogHelper.Info(strLog);
throw ex;
}
finally
{
//清空缓冲区、关闭流
if (fs != null)
{
fs.Flush();
fs.Close();
}
}
}
#endregion private static byte[] ConvertHtmlTextToPDF(string htmlText)
{
if (string.IsNullOrEmpty(htmlText))
{
return null;
}
//避免当htmlText无任何html tag标签的纯文字时,转PDF时会挂掉,所以一律加上<p>标签
//htmlText = "<p>" + htmlText + "</p>"; MemoryStream outputStream = new MemoryStream();//要把PDF写到哪个串流
byte[] data = Encoding.UTF8.GetBytes(htmlText);//字串转成byte[]
MemoryStream msInput = new MemoryStream(data);
Document doc = new Document();//要写PDF的文件,建构子没填的话预设直式A4
PdfWriter writer = PdfWriter.GetInstance(doc, outputStream); //PageEventHelper pageEventHelper = new PageEventHelper();
//writer.PageEvent = pageEventHelper;
//指定文件预设开档时的缩放为100%
PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, , doc.PageSize.Height, 1f); //开启Document文件
doc.Open(); //使用XMLWorkerHelper把Html parse到PDF档里
//XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msInput, null, Encoding.UTF8);
XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msInput, null, Encoding.UTF8, new UnicodeFontFactory()); //XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msInput, null, Encoding.UTF8, new UnicodeFontFactory());
//将pdfDest设定的资料写到PDF档
PdfAction action = PdfAction.GotoLocalPage(, pdfDest, writer);
writer.SetOpenAction(action); ////手工加内容
//doc.NewPage();
////要先定义中文字体
//BaseFont BF_Light = BaseFont.CreateFont(@"C:\Windows\Fonts\simsun.ttc,0", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
////要设置字体和大小
//var p = new Paragraph("合同信息", new Font(BF_Light, 13));
//PdfPTable table = new PdfPTable(1);
//PdfPCell cell = new PdfPCell(p);
////设置cell属性
//cell.HorizontalAlignment = Element.ALIGN_CENTER;
////添加单元格
//table.AddCell(cell);
//doc.Add(table); doc.Close();
msInput.Close();
outputStream.Close();
//回传PDF档案
return outputStream.ToArray();
} #region 创建PDF文档
/// <summary>
/// 生成PDF
/// </summary>
/// <param name="strHtmlData">HTML内容</param>
/// <param name="filePath">文件路径</param>
/// <param name="fileName">文件名</param>
public static bool CreatePdf(string filePath, string fileName, PdfPTable dt)
{
FileStream fs = null;
try
{
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
//获得字节数组
byte[] bPDF = CreatePdf(dt); if (bPDF == null)
{
return false;
} fs = new FileStream(Path.Combine(filePath, fileName), FileMode.Create); //开始写入
fs.Write(bPDF, , bPDF.Length);
return true;
}
catch (Exception)
{
throw;
}
finally
{
//清空缓冲区、关闭流
if (fs != null)
{
fs.Flush();
fs.Close();
}
}
} /// <summary>
/// 创建PDF
/// </summary>
/// <param name="htmlText"></param>
/// <returns></returns>
private static byte[] CreatePdf(PdfPTable pdfTable)
{
MemoryStream outputStream = new MemoryStream();//要把PDF写到哪个串流
Document doc = new Document();//要写PDF的文件,建构子没填的话预设直式A4
PdfWriter writer = PdfWriter.GetInstance(doc, outputStream);
//指定文件预设开档时的缩放为100%
PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, , doc.PageSize.Height, 1f); //开启Document文件
doc.Open();
//将pdfDest设定的资料写到PDF档
PdfAction action = PdfAction.GotoLocalPage(, pdfDest, writer);
writer.SetOpenAction(action); //手工加内容
doc.NewPage();
doc.Add(pdfTable); var row = pdfTable.Rows[pdfTable.Rows.Count];
//iTextSharp.text.Image splitline = iTextSharp.text.Image.GetInstance(@"E:\WorkCodes\YeWu\YCloud.MFBP.Web\Images\yaoshi.png");
//splitline.ScalePercent(12f); //图片比例
//splitline.SetAbsolutePosition(doc.PageSize.Width- doc.PageSize.Width/3*2, doc.PageSize.Height - doc.PageSize.Height/5*4); doc.Close();
outputStream.Close();
//回传PDF档案
return outputStream.ToArray();
} #endregion
} public class UnicodeFontFactory : FontFactoryImp
{
static string fontPath = Environment.GetFolderPath(Environment.SpecialFolder.Fonts); //arial unicode MS是完整的unicode字型。
//private static readonly string arialFontPath = Path.Combine(fontPath, "arialuni.ttf");
//宋体。
private static readonly string stFontPath = Path.Combine(fontPath, "simsun.ttc,0"); public override Font GetFont(string fontname, string encoding, bool embedded, float size, int style, BaseColor color, bool cached)
{
BaseFont baseFont = BaseFont.CreateFont(stFontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
return new Font(baseFont, size, style, color);
}
} public class PageEventHelper : PdfPageEventHelper
{
PdfContentByte cb;
PdfTemplate template; public override void OnOpenDocument(PdfWriter writer, Document document)
{
cb = writer.DirectContent;
template = cb.CreateTemplate(, );
} public override void OnStartPage(PdfWriter writer, Document document)
{
base.OnStartPage(writer, document);
} public override void OnEndPage(PdfWriter writer, Document document)
{
base.OnEndPage(writer, document); String text = "第" + writer.PageNumber.ToString() + "页"; UnicodeFontFactory info = new UnicodeFontFactory();
float len = ;
iTextSharp.text.Rectangle pageSize = document.PageSize;
cb.SetRGBColorFill(, , ); string fontPath = Environment.GetFolderPath(Environment.SpecialFolder.Fonts);
string stFontPath = Path.Combine(fontPath, "simsun.ttc,0");
BaseFont baseFont = BaseFont.CreateFont(stFontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED); cb.BeginText();
cb.SetFontAndSize(baseFont, );
cb.SetTextMatrix(document.LeftMargin, pageSize.GetBottom(document.BottomMargin));
cb.ShowText(text); cb.EndText(); cb.AddTemplate(template, document.LeftMargin + len, pageSize.GetBottom(document.BottomMargin));
} public override void OnCloseDocument(PdfWriter writer, Document document)
{
base.OnCloseDocument(writer, document); string fontPath = Environment.GetFolderPath(Environment.SpecialFolder.Fonts);
string stFontPath = Path.Combine(fontPath, "simsun.ttc,0");
BaseFont baseFont = BaseFont.CreateFont(stFontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED); template.BeginText();
template.SetFontAndSize(baseFont, );
template.SetTextMatrix(, );
template.ShowText("共" + writer.PageNumber + "页");
template.EndText();
} } }
pdf转换的更多相关文章
- Python 将pdf转换成txt(不处理图片)
上一篇文章中已经介绍了简单的python爬网页下载文档,但下载后的文档多为doc或pdf,对于数据处理仍然有很多限制,所以将doc/pdf转换成txt显得尤为重要.查找了很多资料,在linux下要将d ...
- ABBYY如何把PDF转换Excel
我们都知道2007以上版本的Office文档,是可以直接将文档转存为PDF格式文档的.那么反过来,PDF文档可以转换成其他格式的文档吗?这是大家都比较好奇的话题.如果可以以其他格式进行保存,就可以极大 ...
- ABBYY把pdf转换成word的方法
有时候我们在网上下载的资料文献是PDF格式文档,遇到喜欢的字句总忍不住想要收藏起来,但是PDF文档不同于普通的Word文档可以直接进行复制粘贴,需要下载安装相关的编辑工具,才能对文字内容进行编辑.倒不 ...
- 如何用ABBYY把PDF转换成PPT
在电子科技迅速发展的今天,文件格式转换并不是什么稀罕事,因为现在都是电子化办公,出现很多文件格式,但是不同的场合需要的格式不同,所以常常需要进行文件格式的转换.PDF转换成PPT也是众多文件格式转换中 ...
- 利用jpedal进行pdf转换成jpeg,jpg,png,tiff,tif等格式的图片
项目中运用到pdf文件转换成image图片,开始时使用pdfbox开源库进行图片转换,但是转换出来的文件中含有部分乱码的情况.下面是pdfBox 的pdf转换图片的代码示例. try{ String ...
- C#技术分享【PDF转换成图片——13种方案】(2013-07-25重新整理)
原文:C#技术分享[PDF转换成图片--13种方案](2013-07-25重新整理) 重要说明:本博已迁移到 石佳劼的博客,有疑问请到 文章新地址 留言!!! 写在最前面:为了节约大家时间,撸主把最常 ...
- 利用pdf2swf将PDF转换成SWF
将PDF转换成SWF可以使用SWFTools工具中的pdf2swf(http://www.swftools.org/),CSDN快速免积分下载地址http://download.csdn.net/de ...
- 推荐一款免费的PDF转换工具 | PDFCandy
相信大家在用的PDF转换工具也很多,下面良心推荐这款软件(PDFCandy)给大家,方便在今后的工作中进行运用.提高大家的工作效率. PDFCandy分为两种:网页端和客户端.(根据大家的喜好度来进行 ...
- pdf转换成word转换器免费版
在平时的办公中,我们只需要有一款比较好用的pdf转换成word转换器,就能提高我们的工作效率,但是国内外的pdf转换成word转换器应该怎么选呢?小编因为是文职工作者,所以在日常的实践中选出了ABBY ...
- pdf转换成可在线浏览的电子杂志zmaker_pdf
zmaker是曾经国内最流行的电子杂志制作软件,可惜可惜,不过幸好有人给发布了 最新版的 其实主要是2个流程 一个是软件的安装 软件的下载和安装请参考 官方教材 http://bbs.emaghome ...
随机推荐
- Mysql事务代码
/// <summary> /// 删除相册 /// </summary> /// <param name="id"></param> ...
- hadoop的目录结构介绍
hadoop的目录结构介绍 解压缩hadoop 利用tar –zxvf把hadoop的jar包放到指定的目录下. tar -zxvf /home/software/aa.tar.gz -C /home ...
- 依赖作用域之<scope>test</scope>
经常在代码中看到依赖的作用域为<scope>test</scope>,它的作用是,只能在test目录(通过右键->Make Directory as->Test S ...
- six库 解决python2的项目如何能够完全迁移到python3
six库 解决python2的项目如何能够完全迁移到python3 SIX是用于python2与python3兼容的库. 它存在的目的是为了拥有无需修改即可在Python 2和Python 3上同时工 ...
- python-day31(正式学习)
一.单机架构 应用领域: 植物大战僵尸 office 二.CS架构 应用领域: QQ 大型网络游戏 计算机发展初期用户去取数据,直接就去主机拿,从这里开始就分出了客户端和服务端. 客户端:用户安装的软 ...
- 自定义字段的设计与实现(Java实用版)
前言 自定义字段又叫做"开放模型",用户可以根据自已的需求,添加需要的字段,实现个性化定制. 使用自定义字段的目的,使用自定义字段解决哪些问题 如现有一套CRM系统,客户模块中客户 ...
- maven引用本地jar,并打包部署
由于项目需要的一个jar在maven仓库里没有,又不想把jar手动导入仓库.然而百度的几个处理方式都是一样的方法,我却没有一个成功的.于是就请教了大神,大神也是各种测试,终于成功实现了,实现如下: 新 ...
- MySQL存储引擎MyISAM和InnoDB有哪些区别?
一.MyISAM和InnoDB的区别有哪些? 1.InnoDB支持事务,MyISAM不支持.对于InnoDB每一条SQL语言都默认封装成事务,自动提交,这样会影响速度,所以最好把多条SQL语言放在be ...
- 为什么单线程的Redis却能支撑高并发
Redis的高并发和快速原因 redis是基于内存的,内存的读写速度非常快: 核心是基于非阻塞的IO多路复用机制: redis是单线程的,反而省去了很多上下文切换线程的时间: 为什么Redis是单线程 ...
- python之jupyter安装与使用
Jupyter Notebook 的本质是一个 Web 应用程序,便于创建和共享文学化程序文档,支持实时代码,数学方程,可视化和 markdown.用途包括:数据清理和转换,数值模拟,统计建模,机器学 ...