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) { } } } }