假设我有一个三页PDF,其中三个都有AcroFields。我需要能够生成一个新的PDF,第2页重复N次。第2页的每个新实例都需要修改字段名称,以使它们与第2页的其他实例不同。在解决此问题的人之前是否可以提供语法示例?
答案 0 :(得分:0)
MergeForms2示例中对此进行了解释。您应该将文档拆分为3个文档,每个文档都有一个页面。使用renameFields()
方法创建第二页的变体。
连接表单是这样完成的:
Document document = new Document();
PdfCopy copy = new PdfCopy(document, new FileOutputStream(dest));
copy.setMergeFields();
document.open();
List<PdfReader> readers = new ArrayList<PdfReader>();
for (int i = 0; i < 3; ) {
PdfReader reader = new PdfReader(renameFields(src, ++i));
readers.add(reader);
copy.addDocument(reader);
}
document.close();
for (PdfReader reader : readers) {
reader.close();
}
常见的错误是忘记setMergeFields()
方法。
答案 1 :(得分:0)
这可以工作但生成一个大文件。我想这是因为第2页上的图像多次重复而不是重复使用。
public static void ExpandRepeatingPages(string sourcePdfPath, string outputPdfPath)
{
/* figure out how many pages we are working with */
var transientPdfReader = new PdfReader(sourcePdfPath);
var numberOfPages = transientPdfReader.NumberOfPages;
transientPdfReader.Close();
var outputFileStream = new FileStream(outputPdfPath, FileMode.Create);
var pdfCopyFields = new PdfCopyFields(outputFileStream);
foreach (var pageNumber in Enumerable.Range(1, numberOfPages))
{
var pdfBytes = ExtractPageToBytes(sourcePdfPath, pageNumber);
var pdfReader = new PdfReader(pdfBytes);
pdfCopyFields.AddDocument(pdfReader);
pdfReader.Close();
if (pageNumber == 2)
{
foreach (var extraPageNumber in Enumerable.Range(2, 200))
{
var extraPagePdfBytes = RenamePageFields(pdfBytes, extraPageNumber);
pdfReader = new PdfReader(extraPagePdfBytes);
pdfCopyFields.AddDocument(pdfReader);
pdfReader.Close();
}
}
}
pdfCopyFields.Close();
}
public static byte[] ExtractPageToBytes(string sourcePdfPath, int pageNumber)
{
using (var memoryStream = new MemoryStream())
{
var pageNumbers = new System.Collections.ArrayList { pageNumber };
var pdfReader = new PdfReader(sourcePdfPath);
var pdfCopyFields = new PdfCopyFields(memoryStream);
pdfReader.SelectPages(pageNumbers);
pdfCopyFields.AddDocument(pdfReader);
pdfReader.RemoveUnusedObjects();
pdfCopyFields.Close();
pdfReader.Close();
return memoryStream.ToArray();
}
}
private static byte[] RenamePageFields(byte[] pdfBytes, int pageNumber)
{
using (var memoryStream = new MemoryStream())
{
var pdfReader = new PdfReader(pdfBytes);
var pdfStamper = new PdfStamper(pdfReader, memoryStream);
var acroFields = pdfStamper.AcroFields;
var fieldNames = acroFields.Fields.Keys.Cast<String>().ToList();
foreach (var fieldName in fieldNames)
{
var newName = String.Format("{0}_{1}", fieldName, pageNumber);
acroFields.RenameField(fieldName, newName);
}
pdfStamper.Close();
pdfReader.Close();
return memoryStream.ToArray();
}
}