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 ...
随机推荐
- IDEA项目目录里下找不到src,但是src确实存在的的解决方案
写代码的时候可能出现写着写着src就找不到了,我个人认为是触发了热键导致src被隐藏了,下面就是设置src可见和不可见的操作 这个其实是被隐藏了,打开就好,位置如下:
- Hive 教程(一)-安装与配置解析
安装就安装 ,不扯其他的 hive 依赖 在 hive 安装前必须具备如下条件 1. 一个可连接的关系型数据库,如 Mysql,postgresql 等,用于存储元数据 2. hadoop,并启动 h ...
- JAVA基础:接口
接口声明: interface 接口名 实现接口: class 类名 implements 接口名 接口特点: 1. 接口中的成员变量默认都是public.static.final类型的,必须被显式初 ...
- linux centos系统安装
1.下载镜像 https://www.centos.org/download/ DVD ISO 一般下载这个 erverything ISO 包含所有工具的版本 Minimal ISO最小启动版本 2 ...
- Redis windows服务器配置可远程连接
Redis配置远程可访问:修改redis.conf或redis.windows-service.conf配置文件. 具体通过 1:将绑定的本机给注释掉,找到这行 bind 127.0.0.1,然后在前 ...
- 一个java文件中有几个类,编译后有几个class文件?
在一个源文件中用class关键字定义了几个类,编译的时候就会产生几个字节码文件
- 转换byte(十进制)为图形(大小写字母,符号)
/** * 转换byte(十进制)为字母 */ public static String ByteToLetter (byte[] chars) { String Letter = "&qu ...
- JS中的事件传播流程
JS中的事件传播流程 1,Javascript与HTML之间的交互是通过事件实现的. 事件,就是文档或浏览器窗口中发生的一些特定的交互瞬间. 可以使用侦听器来预定事件,以便事件发生时执行相应代码. 2 ...
- vue iview面包屑
简单看一下vue,iview的面包屑怎么写呢? 简单的思路:1.获取到路由记录$route.matched 2.渲染 效果: 一.$route.matched 官网地址:https://router. ...
- 一个页面多图表展示(四个div的方式)
效果如图所示,一个页面四个div,每个div里面展示相应的数据,因为这种效果会有点麻烦,而且不太雅观我就换了一种写法,一个div里面用四个图表,共用一个图例,先放上这个方式的效果图和源码,后期会再发布 ...