日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > C# >内容正文

C#

C#使用iTextSharp操作PDF文件

發布時間:2023/12/4 C# 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C#使用iTextSharp操作PDF文件 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

概述

html文件怎么轉成PDF文件?有的招聘網上的簡歷導成DOC文件,不能直接使用,這樣造成很大的困擾,那么它還有一個格式,那就是html格式。將文件導出成html格式,然后再轉成PDF文件,這樣便可以直接使用了。平常在項目中也是很多這樣的需求,需要把內容轉成pdf文件。

下面我們來看下使用? iTextSharp實現HTML轉PDF的方法。

代碼實現

1、nuget 安裝iTextSharp。

using iTextSharp.text; using iTextSharp.text.pdf;

2、將Html文檔轉換為pdf。

/// <summary>/// 將Html文檔轉換為pdf/// </summary>/// <param name="htmlText"></param>/// <returns></returns>public byte[] ConvertHtmlTextToPDF(string htmlText){if (string.IsNullOrEmpty(htmlText))return null;//避免當htmlText無任何html tag標簽的純文字時,轉PDF時會掛掉,所以一律加上<p>標簽htmlText = "<p>" + htmlText + "</p>";using (var outputStream = new MemoryStream()){byte[] data = Encoding.UTF8.GetBytes(htmlText);var msInput = new MemoryStream(data);var doc = new Document();//pdf文檔,默認A4格式。var writer = PdfWriter.GetInstance(doc, outputStream);doc.Open();//使用XMLWorkerHelper把Html parse到PDFiTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msInput, null, Encoding.UTF8, new UnicodeFontFactory());//指定默認縮放比例為100%var pdfDest = new PdfDestination(PdfDestination.XYZ, 0, doc.PageSize.Height, 1f);//將默認設置寫入pdfvar action = PdfAction.GotoLocalPage(1, pdfDest, writer);writer.SetOpenAction(action);doc.Close();msInput.Close();outputStream.Close();return outputStream.ToArray();}}

3、Unicode 字體支持。

/// <summary>/// Unicode 字體支持/// </summary>public class UnicodeFontFactory : FontFactoryImp{public override Font GetFont(string fontname, string encoding, bool embedded, float size, int style, BaseColor color, bool cached){//使用微軟雅黑字體解決中文亂碼的問題,因為雅黑字體為字體集合所以需要使用,0來指定具體的字體。//var chineseFontPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "msyh.ttc,0");//宋體//BaseFont baseFont = BaseFont.CreateFont(@"c:\Windows\Fonts\simsun.ttc,0", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);//黑體BaseFont baseFont = BaseFont.CreateFont(@"c:\Windows\Fonts\SIMHEI.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);//var baseFont = BaseFont.CreateFont(chineseFontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);return new Font(baseFont, size, style, color);}}

4、調用生成。

string content = temp.Content;foreach (var dict in dicts){content = content.Replace("{{" + dict.Key + "}}", dict.Value);}var path = _esignInfo.Value.ContractPath;//if (entity.ContractType == ContractType.First)//{// path += "/" + appId + "/Agreements";//}entity.OriginalFileUrl = _pdfHelper.WritePdfFile(content, contractNo, path, "PDF");bool isSucc = !String.IsNullOrEmpty(entity.OriginalFileUrl);

總結

以上是生活随笔為你收集整理的C#使用iTextSharp操作PDF文件的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。