Reputation: 37
I have created a reader for Input file and one for the Markup file. I am not sure if I should loop through the annotations and then add them one by one to the output or if there is a way to pull all the annotations from the markup file and add them to the input file retaining their x,z coordinates.
I have the below code, and I am not sure what to do at the commented section. The AddAnnotation method only takes PdfAnnotation as input but I am not sure how to convert the PdfDictionary to 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();
}
}
I tried another variation after I found new GetAnnotations method in iText7. Here the code runs fine but I am not able to open the O/P file and get an error that the file is corrupted. Also when I ran inputDoc.Close() instead of the last line given below, I got an error “Pdf indirect object belongs to other PDF document. Copy object to current pdf document.”
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);
Upvotes: 3
Views: 606
Reputation: 1177
Maybe try this :
if (annots != null)
{
for (int j = 0; j < annots.Size(); j++)
{
PdfDictionary annotItem = annots.GetAsDictionary(i);
PdfLineAnnotation lineAnnotation = new PdfLineAnnotation(annotItem);
page.AddAnnotation(lineAnnotation);
}
}
If it doesn't work, here is some documentation (unfortunately in Java)
If you could post Pdf with annotations you wish to copy - maybe I can debug and try something more.
Upvotes: 1