[英]Using iTextSharp to add repeating data to an existing PDF?
我將使用iTextSharp將數據插入到圖形部門創建的PDF中。 這些數據大多數是簡單的數據到字段的映射,但是一些數據是需要添加的項目的列表(例如,產品數據;用戶可以擁有任意數量的產品,並且需要為所有產品顯示數據) 。
是否可以使用iTextSharp做到這一點? 顯然,無法使用一定數量的字段來創建PDF模板,因為無法知道將有多少個字段-它可能是1、10或什至100。 我需要做的是“重用” PDF的一部分,並對循環中的每個項目重復該部分。
那可行嗎?
過去,我需要做類似的事情。 我需要創建一個圖像和內容數量未知的PDF。 在我的情況下,“入口”是由圖片和一組字段定義的。
我所做的是有一個醫生。 作為“條目”模板。 然后,我生成了一個溫度。 每個“條目”的pdf文件,並將生成的文件名存儲在列表中。 在處理完所有“條目”之后,我將所有臨時pdf文檔合並為一個最終文檔。
這里有一些代碼可以給你一個更好的主意(它不是可編譯的,只是作為參考,因為我從較早的項目中提取了某些部分)。
List<string> files = new List<string>(); // list of files to merge
foreach (string pageId in pages)
{
// create an intermediate page
string intermediatePdf = Path.Combine(_tempPath, System.Guid.NewGuid() + ".pdf");
files.Add(intermediatePdf);
string pdfTemplate = Path.Combine(_templatePath, _template);
CreatePage(pdfTemplate, intermediatePdf, pc, pageValues, imageMap, tmd);
}
// merge into resulting pdf file
string outputFolder = "~/Output/";
if (preview)
{
outputFolder = "~/temp/";
}
string pdfResult = Path.Combine(HttpContext.Current.Server.MapPath(outputFolder), Guid.NewGuid().ToString() + ".pdf");
PdfMerge.MergeFiles(pdfResult, files);
//////////////////////////////////////////////////////////////////////////
// delete temporary files...
foreach (string fd in files)
{
File.Delete(fd);
}
return pdfResult;
這是合並模板的代碼:
public class PdfMerge
{
public static void MergeFiles(string destinationFile, List<string> sourceFiles)
{
int f = 0;
// we create a reader for a certain document
PdfReader reader = new PdfReader(sourceFiles[f]);
// we retrieve the total number of pages
int n = reader.NumberOfPages;
// step 1: creation of a document-object
Document document = new Document(reader.GetPageSizeWithRotation(1));
// step 2: we create a writer that listens to the document
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationFile, FileMode.Create));
// step 3: we open the document
document.Open();
PdfContentByte cb = writer.DirectContent;
PdfImportedPage page;
int rotation;
// step 4: we add content
while (f < sourceFiles.Count)
{
int i = 0;
while (i < n)
{
i++;
document.SetPageSize(reader.GetPageSizeWithRotation(i));
document.NewPage();
page = writer.GetImportedPage(reader, i);
rotation = reader.GetPageRotation(i);
if (rotation == 90 || rotation == 270)
{
cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
}
else
{
cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
}
f++;
if (f < sourceFiles.Count)
{
reader = new PdfReader(sourceFiles[f]);
// we retrieve the total number of pages
n = reader.NumberOfPages;
}
}
// step 5: we close the document
document.Close();
}
}
希望能幫助到你!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.