empira / MigraDoc-1.5

MigraDoc Foundation - Creating documents on the fly
MIT License
218 stars 125 forks source link

Adding PDF annotation to Migradoc document object #25

Closed Sicos1977 closed 5 years ago

Sicos1977 commented 5 years ago

Hi,

Is it possible to add a PDFAnnotation to a document object?

I made the document like this

            var document = new Document
            {
                Info = {Author = "ImageConverter"}, 
                UseCmykColor = true
            };

And added some images like this

            var paragraph = section.AddParagraph();
            image = paragraph.AddImage(imageString);
           .....

And tried to add a pdfannotation like this

            var pdfTextAnnotation = new PdfTextAnnotation
            {
                Icon = PdfTextAnnotationIcon.Note,
                Title = "Image meta-data",
                Contents = stringBuilder.ToString(),
                //Rectangle = new PdfRectangle(new XRect(30, 500, 30, 30)),
                Flags = PdfAnnotationFlags.Locked
            };

            var pdfDocument = new PdfDocument();
            var page = pdfDocument.AddPage();
            var gfx = XGraphics.FromPdfPage(page);
            page.Annotations.Add(pdfTextAnnotation);

            var documentRenderer = new DocumentRenderer(document);
            documentRenderer.PrepareDocument();

            var pdfRenderer = new PdfDocumentRenderer {Document = document};
            pdfRenderer.RenderDocument();
            pdfRenderer.WriteDocumentInformation();
            pdfRenderer.PdfDocument.Save("d:\\test.pdf");

Everything works, I see the images but for some reason the annotation is not visible in the document. Am I doing something wrong?

TH-Soft commented 5 years ago

Maybe add the PdfTextAnnotation after RenderDocument has completed.

Or maybe use RenderPage instead of RenderDocument as shown in this sample: https://forum.pdfsharp.net/viewtopic.php?f=8&t=3172

Sicos1977 commented 5 years ago

Thanks... I solved it like this.

            var pdfRenderer = new PdfDocumentRenderer {Document = document};
            pdfRenderer.RenderDocument();
            var page = pdfRenderer.PdfDocument.Pages[0];

            var pdfTextAnnotation = new PdfTextAnnotation
            {
                Icon = PdfTextAnnotationIcon.Note,
                Title = "Image meta-data",
                Contents = "Bla die bla bla",
                Rectangle = new PdfRectangle(new XRect(30, page.Height, 30, 30)),
                Flags = PdfAnnotationFlags.Locked
            };

            page.Annotations.Add(pdfTextAnnotation);

            pdfRenderer.WriteDocumentInformation();
            pdfRenderer.PdfDocument.Save(outputFile);