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 ...
随机推荐
- elasticsearch的cross_fields查询
1.most_fields 这种方式搜索也存在某些问题 它不能使用 operator 或 minimum_should_match 参数来降低次相关结果造成的长尾效应. 2.词 peter 和 smi ...
- 云数据库RDS SQL Server 版
云数据库RDS SQL Server版是一种可弹性伸缩的在线数据库服务,并具备自动监控.备份.容灾恢复等方面的全套解决方案,彻底解决数据库运维的烦恼 请观看视频简介 SQL Server是发行最早的商 ...
- P2670 【扫雷游戏】
题面哦~~ lalala~~~ 这题数据并不大,最大不过100*100,所以果断穷举 其实本来我是想边读边做的,但读入是个问题. 主要思路呢,就是读完之后穷举一边,只要是炸弹,就把周围一圈8个加一遍 ...
- 协程+IO切换+小爬虫
from gevent import monkeymonkey.patch_all() import geventimport requests def f1(url): print(f'GET:{u ...
- 安装PIG
下载Pig 能够执行在Hadoop 0.20.* http://mirror.bit.edu.cn/apache/pig/pig-0.11.1/pig-0.11.1.tar.gz 也能够依据你的Had ...
- 剑指offer-构建乘积数组-数组-python
题目描述 给定一个数组A[0,1,...,n-1],请构建一个数组B[0,1,...,n-1],其中B中的元素B[i]=A[0]*A[1]*...*A[i-1]*A[i+1]*...*A[n-1].不 ...
- MySQL存储引擎知多少
MySQL是我们经常使用的数据库处理系统(DBMS),不知小伙伴们有没有注意过其中的“存储引擎”(storage_engine)呢?有时候面试题中也会问道MySQL几种常用的存储引擎的区别.这次就简短 ...
- echarts属性的设置
// 全图默认背景 // backgroundColor: ‘rgba(0,0,0,0)’, // 默认色板 color: ['#ff7f50','#87cefa','#da70d6','#32cd ...
- LLVM 安装教程(包安装)
LLVM 安装教程 环境:ubuntu16.04 llvm-4.0 clang-4.0 步骤: 1.依赖库安装 $ sudo apt-get install build-essential curl ...
- bagging and boosting
bagging 侧重于降低方差 方差-variance 方差描述的是预测值的变化范围,离散程度,也就是离期真实值的距离.方差过大表现为过拟合,训练数据的预测f-score很高,但是验证或测试数据的预测 ...