C#使用iTextSharp生成PDF的示例代碼
需求
按數(shù)據(jù)層級生成PDF文件,要有目錄,目錄里要有真實的頁碼,附件內(nèi)容用表格顯示,每頁要有頁碼,大標題 做為封面當獨顯示一頁,
PDF內(nèi)容
大標題,
目錄(里有對應的頁碼)
正文 里有 表格
每頁還有頁碼
實現(xiàn)代碼
/// <summary>
/// 生成 pdf 文件
/// </summary>
/// <param name="model">實體對象</param>
/// <param name="caseDetailsViewModels">數(shù)據(jù)LIST</param>
/// <param name="TargetPath">目標文件路徑</param>
/// <param name="NewFileName">文件名</param>
/// <returns></returns>
private static string createPDF(ViewModel model, List<DetailsViewModel> DetailsViewModels, string TargetPath, string NewFileName)
{
string outMergeFile = TargetPath + NewFileName;
if (Directory.Exists(outMergeFile))
{
Directory.Delete(outMergeFile);
}
var pageSize = PageSize.A4;
iTextSharp.text.Document document = new iTextSharp.text.Document(pageSize);
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outMergeFile, FileMode.Create));
try
{
document.Open();
#region 字體
Font BF_Light = FontFactory.GetFont(@"C:\Windows\Fonts\simsun.ttc,0", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font bigTitle_Light = FontFactory.GetFont(@"C:\Windows\Fonts\simsun.ttc,0", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
bigTitle_Light.Size = 20;
Font title_Light = FontFactory.GetFont(@"C:\Windows\Fonts\simsun.ttc,0", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
title_Light.SetColor(0, 0, 255);
title_Light.Size = 16;
Font body_Light = FontFactory.GetFont(@"C:\Windows\Fonts\simsun.ttc,0", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
body_Light.Size = 12;
//var titleFont = GetFont();
//titleFont.SetStyle(Font.BOLD);
//titleFont.Color = BaseColor.BLACK;
//titleFont.Size = 16;
//new Font(baseFont2, 20f)
#endregion
//第一頁
//段落 大標題
#region 大標題
var titleParagraph = new Paragraph(new Phrase(model.TitleModel.F_ContentStr, bigTitle_Light));
float x = 300;
float y = document.PageSize.Height / 2;
ColumnText.ShowTextAligned(writer.DirectContent, Element.ALIGN_CENTER, titleParagraph, x, y, 0);
#endregion
//第二頁
#region 增加目錄頁
document.NewPage();
var catalogueP = new Paragraph(new Phrase("目錄", body_Light));
//catalogueP.IndentationLeft = 160;
//document.Add(catalogueP);
//頁頭顯示的位置
ColumnText.ShowTextAligned(writer.DirectContent, Element.ALIGN_CENTER, catalogueP, document.PageSize.Width / 2, document.Top, 0);
foreach (var item in model.TwoTitleList)
{
Chunk leader = new Chunk(new DottedLineSeparator(), 400);//400
var F_ContentStrTxt = item.F_ContentStr.Trim();
Paragraph pp = new Paragraph(new Phrase(" " + F_ContentStrTxt, BF_Light));
pp.Add(leader);
pp.Add(new Phrase(!string.IsNullOrEmpty(item.F_Page) ? item.F_Page : "1~1", BF_Light));
document.Add(pp);
}
#endregion
//正文
//第三頁
#region 正文
int iPageNum = 3;
int beginPageNum = 3;
BaseFont baseFont2 = BaseFont.CreateFont(@"C:\Windows\Fonts\simsun.ttc,0", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
document.NewPage();
foreach (var item in model.TwoTitleList)
{
iPageNum = writer.PageNumber;
//標題
document.Add(new Paragraph(new Phrase(item.F_ContentStr, title_Light)));
foreach (var itemThree in item.ThreeContentList)
{
itemThree.F_ContentStr = itemThree.F_ContentStr.Replace("\r\n", string.Empty);
//內(nèi)容
if (itemThree.F_ContentStr.Contains("</p>"))
{
var contentStr = itemThree.F_ContentStr.Replace("<p>", string.Empty);
var contentList = contentStr.Split("</p>");
foreach (var itemCon in contentList)
{
var itemConTxt = itemCon.Replace("\n", string.Empty).Trim();
var bydyPhrase = new Paragraph(new Phrase(" " + itemConTxt, body_Light));
document.Add(bydyPhrase);
if (writer.PageNumber > iPageNum)
{
writePageNumber(document, writer, BF_Light);
}
}
}
else
{
var txt = itemThree.F_ContentStr.Replace("\n", string.Empty).Trim();
document.Add(new Paragraph(new Phrase(" " + txt, body_Light)));
}
}
//if (writer.PageNumber > iPageNum)
//{
item.F_Page = string.Format("{0}~{1}", iPageNum, writer.PageNumber);
iPageNum = writer.PageNumber;
//}
}
#endregion
#region 附件
if (model.FileList != null && model.FileList.Count > 0)
{
var bydyPhrase1 = new Paragraph(new Phrase(" (一)檢索結果分析列表", body_Light));
document.Add(bydyPhrase1);
document.Add(new Paragraph(new Phrase(" ")));
int groupNum = 1;
foreach (var item in model.FileList)
{
var keywordTxt = item.Keyword.Replace("\n", string.Empty).Trim();
var bydyPhrase = new Paragraph(new Phrase(" " + keywordTxt, body_Light));
document.Add(bydyPhrase);
document.Add(new Paragraph(new Phrase(" ")));
PdfPTable table = new PdfPTable(4);
int[] widths = { 40, 20, 20, 20 };
table.SetWidths(widths);//設置每列的寬度(求和百分比5,10=1,2)
//為pdfpTable的構造函數(shù)傳入整數(shù)3,pdfpTable被初始化為一個三列的表格
//PdfPCell cell = new PdfPCell(new Phrase("第一行 跨3列", BF_Light));
//cell.Colspan = 6;//跨3列
//0=Left, 1=Centre, 2=Right
//table.AddCell(cell);
PdfPCell cell = new PdfPCell(new Phrase("標題", BF_Light));
cell.HorizontalAlignment = 1;
table.AddCell(cell);
PdfPCell cel2 = new PdfPCell(new Phrase("案號", BF_Light));
cel2.HorizontalAlignment = 1;
table.AddCell(cel2);
PdfPCell cel3 = new PdfPCell(new Phrase("是否加入檢索報告", BF_Light));
cel3.HorizontalAlignment = 1;
table.AddCell(cel3);
PdfPCell cel4 = new PdfPCell(new Phrase("未加入檢索報告原因", BF_Light));
cel4.HorizontalAlignment = 1;
table.AddCell(cel4);
foreach (var itemKey in item.KeywordFileList)
{
table.AddCell(new Phrase(itemKey.F_CaseTitle, BF_Light));
table.AddCell(new Phrase(itemKey.F_CaseCode.ToString(), BF_Light));
table.AddCell(new Phrase(itemKey.F_IsAdd ? "是" : "否", BF_Light));
table.AddCell(new Phrase(itemKey.F_NoAddCause, BF_Light));
groupNum++;
}
document.Add(table);
}
}
#endregion
#region 生成案例
if (caseDetailsViewModels != null && caseDetailsViewModels.Count > 0)
{
var bydyPhrase2 = new Paragraph(new Phrase(" (二)檢索案例全文", body_Light));
document.Add(bydyPhrase2);
document.Add(new Paragraph(new Phrase(" ")));
foreach (var item in caseDetailsViewModels)
{
foreach (var itemCase in item.CaseItemList)
{
//標題
itemCase.F_Title = itemCase.F_Title.Replace("\r\n", string.Empty);
var F_TitleTxt = itemCase.F_Title.Trim();
document.Add(new Paragraph(new Phrase(" " + F_TitleTxt, body_Light)));
//內(nèi)容
itemCase.F_Content = itemCase.F_Content.Replace("\r\n", string.Empty);
if (itemCase.F_Content.Contains("</p>"))
{
var contentStr = itemCase.F_Content.Replace("<p>", string.Empty);
var contentList = contentStr.Split("</p>");
foreach (var itemCon in contentList)
{
var itemConTxt = itemCon.Replace("\n", string.Empty).Trim();
var bydyPhrase = new Paragraph(new Phrase(" " + itemConTxt, body_Light));
document.Add(bydyPhrase);
if (writer.PageNumber > iPageNum)
{
writePageNumber(document, writer, BF_Light);
}
}
}
else
{
var F_ContentTxt = itemCase.F_Content.Replace("\n", string.Empty).Trim();
document.Add(new Paragraph(new Phrase(" " + F_ContentTxt, body_Light)));
}
}
}
}
#endregion
}
catch (Exception ex)
{
LogFactory.GetLogger("createReportDetailsPDFCatalogue").Info("createReportDetailsPDFCatalogue 報錯" + ex.Message);
}
finally
{
if (document != null)
{
document.Close();
}
if (writer != null)
{
writer.Close();
}
}
return outMergeFile;
}
/// <summary>
/// 寫頁碼
/// </summary>
/// <param name="document"></param>
/// <param name="writer"></param>
/// <param name="BF_Light"></param>
private static void writePageNumber(iTextSharp.text.Document document, PdfWriter writer, Font BF_Light)
{
Phrase header = new Phrase("第" + (writer.PageNumber).ToString() + "頁", BF_Light);// - 1
//頁腳顯示的位置
ColumnText.ShowTextAligned(writer.DirectContent, Element.ALIGN_CENTER, header, document.PageSize.Width / 2, document.Bottom, 0);
}調(diào)用,注意要調(diào)用兩次,第一次生成時不知道目錄里的內(nèi)容在第幾頁,第一次在生成時收集頁碼。這時會生成一個臨時文件。第二次生成的目錄里的頁碼才是真實有效的數(shù)據(jù)。所以要生成兩次。
就好比你在寫WORD時也是不知道目錄里的內(nèi)容會寫在第幾次,都是一、二級標題和內(nèi)容都寫完后,再去生成目錄的。這里的道理也是一樣的。
var fileNameTempPath = createPDF(model, null, uploadPath, fileNameTemp); var savePath = createPDF(model, caseDetailsViewModels, uploadPath, fileName);
到此這篇關于C#使用iTextSharp生成PDF的示例代碼的文章就介紹到這了,更多相關C# iTextSharp生成PDF內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
C#利用Free Spire.Doc for .NET將RTF文檔轉換為圖片
RTF(Rich Text Format)是一種常見的文檔格式,廣泛應用于文本編輯和文檔交換中,本文我們就來看看C#如何利用Free Spire.Doc for .NET實現(xiàn)將RTF文檔轉換為圖片,感興趣的小伙伴可以了解下2025-12-12
Windows下C#的GUI窗口程序中實現(xiàn)調(diào)用Google Map的實例
這篇文章主要介紹了Windows下C#的GUI窗口程序中實現(xiàn)調(diào)用Google Map的實例,如果只想調(diào)用瀏覽器打開網(wǎng)頁的話可以看文章最后的方法,需要的朋友可以參考下2016-04-04
C#實現(xiàn)讀取DataSet數(shù)據(jù)并顯示在ListView控件中的方法
這篇文章主要介紹了C#實現(xiàn)讀取DataSet數(shù)據(jù)并顯示在ListView控件中的方法,涉及C#操作DataSet及ListView控件的相關技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-10-10

