CODE-Convert Text to PDF in C#
| | | 5 | |
透過程式直接將Text內容轉換成PDF的程式範例,寫來給其他組同事做為系統整合模組開發參考,順便PO文備忘。
要在.NET轉PDF,當然少不了大家都說讚的iTextSharp,程式很簡單,我還順手加了一個遇到"\f" (0x0C) Form Feed符號就強制換新頁的功能。
<%@ Page Language="C#" %><%@ Import Namespace="iTextSharp.text" %><%@ Import Namespace="iTextSharp.text.pdf" %><%@ Import Namespace="System.IO" %><script runat="server">
protected void btnConvert_Click(object sender, EventArgs e)
{//REF: http://www.codeproject.com/KB/graphics/iTextSharpTutorial.aspx Document doc = new Document(PageSize.A4.Rotate());using (MemoryStream ms = new MemoryStream())
{ try {PdfWriter.GetInstance(doc, ms);
doc.Open();
//中文字型問題REF //http://renjin.blogspot.com/2009/01/using-chinese-fonts-in-itextsharp.html string fontPath = Environment.GetFolderPath(
Environment.SpecialFolder.System) +
@"\..\Fonts\kaiu.ttf";BaseFont bfChinese = BaseFont.CreateFont(
fontPath,
BaseFont.IDENTITY_H, //橫式中文BaseFont.NOT_EMBEDDED
);
Font fontChinese = new Font(bfChinese, 8f, Font.NORMAL); StringReader sr = new StringReader(txtInput.Text);string line = null;
while ((line = sr.ReadLine()) != null)
{string[] p = line.Split('\f');
foreach (string s in p)
{ doc.Add(new Paragraph(s, fontChinese));if (p.Length > 1) //表示有換頁符號
doc.NewPage();
}
}
}
catch (DocumentException de) {Response.Write(de.Message);
Response.End();
}
catch (IOException ioe) {Response.Write(ioe.Message);
Response.End();
}
doc.Close();
//Output PDFResponse.Clear();
Response.ContentType = "application/octet-stream"; Response.AddHeader("content-disposition", "attachment;filename=output.pdf");Response.BinaryWrite(ms.ToArray());
Response.End();
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Text to PDF demo</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtInput" runat="server" Height="600px" TextMode="MultiLine"
Width="800px"></asp:TextBox>
<br /><asp:Button ID="btnConvert" runat="server" onclick="btnConvert_Click"
Text="Convert to PDF" />
</div>
</form>
</body>
</html>
Comments
# by lsk
五點還沒到,黑大你就已經在未來先PO文囉~~
# by topcat
來自未來的訊息!!
# by Han
請問如果轉出內容是HTML格式,要如何呈現呢?
# by Alex
iTextSharp 5.0 以後採用 AGPL 授權 黑大 有改用其他 nuget package 嗎? 或是購買 commercial license ?
# by Jeffrey
to Alex,我的理解,若限定企業內部使用,完全不對外提供服務,應該還是可行(如有錯請指正)。參考:https://opensource.stackexchange.com/a/7229