C# Html转pdf文件
using iTextSharp.text; using iTextSharp.text.pdf; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Net; using iTextSharp.tool.xml; namespace WebApplication1 { public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string htmlText = "<html><body><div>testtest</div></body></html>"; //避免当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); //指定文件预设开档时的缩放为100% PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, doc.PageSize.Height, 1f); //开启Document文件 doc.Open(); //使用XMLWorkerHelper把Html parse到PDF档里 // XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msInput, null, Encoding.UTF8, new UnicodeFontFactory()); XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msInput, null, Encoding.UTF8); //将pdfDest设定的资料写到PDF档 PdfAction action = PdfAction.GotoLocalPage(1, pdfDest, writer); writer.SetOpenAction(action); doc.Close(); msInput.Close(); outputStream.Close(); //回传PDF档案 var bytes = outputStream.ToArray(); var ret = Convert.ToBase64String(bytes); try { string strbase64 = ret; strbase64 = strbase64.Replace(' ', '+'); System.IO.MemoryStream stream = new System.IO.MemoryStream(Convert.FromBase64String(strbase64)); System.IO.FileStream fs = new System.IO.FileStream("D:\\证件1.pdf", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write); byte[] b = stream.ToArray(); //byte[] b = stream.GetBuffer(); fs.Write(b, 0, b.Length); fs.Close(); } catch (Exception ex) { } } } }
记得收藏并关注,掌握更多相关知识!!!
分类:
C#
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· 【.NET】调用本地 Deepseek 模型
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 上周热点回顾(2.17-2.23)