【发布时间】:2017-08-04 08:19:00
【问题描述】:
我为输入文件和标记文件创建了一个阅读器。我不确定是否应该遍历注释,然后将它们一一添加到输出中,或者是否有办法从标记文件中提取所有注释并将它们添加到输入文件中,并保留它们的 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);
【问题讨论】:
-
你用什么库来阅读 pdf 的?
-
@Piotr - 我正在使用 iText7