在一个 pdf 的所有页面中添加一组批注 PDF 到另一个 pdf 的所有页面中,并创建一个新的输出 pdf



我已经为输入文件创建了一个阅读器,为标记文件创建了一个阅读器。我不确定我是否应该循环访问注释,然后将它们一一添加到输出中,或者是否有办法从标记文件中提取所有注释并将它们添加到输入文件中,保留其 x,z 坐标。

我有下面的代码,我不确定在注释部分该怎么做。AddAnnotation方法仅将PdfAnnotation作为输入,但我不确定如何将PdfDictionary转换为PdfAnnotaiton。

class Program
{
public static string inputFile = @"E:pdf-sample.pdf";
public static string markupFile = @"E:StampPdf.pdf";
public static string outputFile = @"E:pdf.pdf";
public static PdfReader inputReader = new PdfReader(inputFile);
public static PdfReader markupReader = new PdfReader(markupFile);
static void Main(string[] args)
{
PdfDocument inputDoc = new PdfDocument(inputReader, new PdfWriter(outputFile));
PdfDocument markupDoc = new PdfDocument(markupReader);
int n = inputDoc.GetNumberOfPages();
for (int i = 1; i <= n; i++)
{
PdfPage page = inputDoc.GetPage(i);
PdfDictionary markupPage = markupDoc.GetFirstPage().GetPdfObject();
PdfArray annots = markupPage.GetAsArray(PdfName.Annots);
if(annots != null)
{
for(int j=0; j < annots.Size(); j++)
{
PdfDictionary annotItem = annots.GetAsDictionary(i);
//******
//page.AddAnnotation(?);
//******
}
}
}
inputDoc.Close();
}
}

在iText7中找到新的GetAnnotations方法后,我尝试了另一种变体。这里的代码运行良好,但我无法打开 O/P 文件并收到文件已损坏的错误。同样,当我运行inputDoc.Close((而不是下面给出的最后一行时,我收到一个错误"Pdf间接对象属于其他PDF文档。将对象复制到当前 pdf 文档。

PdfReader ireader = new PdfReader(inputFile);
PdfDocument inputDoc = new PdfDocument(ireader, new PdfWriter(outputFile));
PdfReader mreader = new PdfReader(markupFile);
PdfDocument markupDoc = new PdfDocument(mreader);
var annots = markupDoc.GetFirstPage().GetAnnotations();
if (annots != null)
{
for (int j = 0; j < annots.Count(); j++)
{
inputDoc.GetFirstPage().AddAnnotation(annots[j]);
}
}
ireader.Close();
mreader.Close();
markupDoc.Close();
inputDoc.SetCloseWriter(true);

也许试试这个:

if (annots != null)
{
for (int j = 0; j < annots.Size(); j++)
{
PdfDictionary annotItem = annots.GetAsDictionary(i);
PdfLineAnnotation lineAnnotation = new PdfLineAnnotation(annotItem);
page.AddAnnotation(lineAnnotation);
}
}

如果它不起作用,这里有一些文档(不幸的是在 Java 中(

http://developers.itextpdf.com/examples/actions-and-annotations/clone-creating-and-adding-annotations

如果您可以发布带有要复制的注释的 Pdf - 也许我可以调试并尝试更多内容。

相关内容

最新更新