0
我正在編寫一個程序來填寫有36個訂單項的PDF訂單。有時會有超過36個項目,因此我希望能夠在保存之前爲剩餘項目添加第二個頁面。這裏是我目前有填充PDF行項目代碼:如何使用iTextSharp的PdfReader和Stamper製作多個頁面?
private SaveResult WritePDF(ref ObservableCollection<OrderLineItem> saveObj)
{
try
{
if (saveObj == null) throw new ArgumentNullException("Save Object is null");
var theForm = ReadResource("LineItemOrderForm");
var sfd = new SaveFileDialog
{
AddExtension = true,
InitialDirectory = DesktopPath,
DefaultExt = ".pdf",
RestoreDirectory = true,
Filter = "Adobe PDF Files (.pdf)|*.pdf",
};
var saveResult = sfd.ShowDialog();
if (saveResult == false) return SaveResult.Cancelled;
var outPath = sfd.FileName;
var timesBasePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "TIMESBD.TTF");
var timesBaseFont = BaseFont.CreateFont(timesBasePath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
using (var pdfReader = new PdfReader(theForm))
{
var fs = new FileStream(outPath, FileMode.Create);
using (var pdfStamper = new PdfStamper(pdfReader, fs))
{
var form = pdfStamper.AcroFields;
form.AddSubstitutionFont(timesBaseFont);
var i = 1;
form.SetField("OrderFormDealerName", Constants.DealerName);
form.SetFieldProperty("OrderFormDealerName", "textcolor", BaseColor.BLACK, null);
foreach (var item in saveObj)
{
form.SetField($"LineItem{i:D2}", item.LineItemNumber.ToString(CultureInfo.InvariantCulture));
form.SetFieldProperty($"LineItem{i:D2}", "textcolor", BaseColor.BLACK, null);
form.SetField($"Qty{i:D2}", item.Quantity.ToString(CultureInfo.InvariantCulture));
form.SetFieldProperty($"Qty{i:D2}", "textcolor", BaseColor.BLACK, null);
form.SetField($"PartNumber{i:D2}", item.PartNumber);
form.SetFieldProperty($"PartNumber{i:D2}", "textcolor", BaseColor.BLACK, null);
form.SetField($"Hinging{i:D2}", item.Hinging.ToString());
form.SetFieldProperty($"Hinging{i:D2}", "textcolor", BaseColor.BLACK, null);
form.SetField($"Finished{i:D2}", item.Finished.ToString());
form.SetFieldProperty($"Finished{i:D2}", "textcolor", BaseColor.BLACK, null);
form.SetField($"UnitPrice{i:D2}", $"{item.UnitPrice:C0}");
form.SetFieldProperty($"UnitPrice{i:D2}", "textcolor", BaseColor.BLACK, null);
form.SetField($"ModPrice{i:D2}", $"{item.ModifyPrice:C0}");
form.SetFieldProperty($"ModPrice{i:D2}", "textcolor", BaseColor.BLACK, null);
form.SetField($"ExtPrice{i:D2}", $"{item.ExtendedPrice:C0}");
form.SetFieldProperty($"ExtPrice{i:D2}", "textcolor", BaseColor.BLACK, null);
i++;
}
pdfStamper.FormFlattening = false;
pdfStamper.Close();
}
pdfReader.Close();
return SaveResult.Success;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "WritePDF()");
return SaveResult.Failure;
}
}
什麼是適應這個代碼來實現我期待的結果的最佳方式?
編輯:我正在使用通過NuGet包管理器安裝的iTextSharp版本5.5.11。