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。