ststeiger / PdfSharpCore

Port of the PdfSharp library to .NET Core - largely removed GDI+ (only missing GetFontData - which can be replaced with freetype2)
Other
1.07k stars 239 forks source link

Adding text highlighting annotation #342

Open wysiwygxy opened 1 year ago

wysiwygxy commented 1 year ago

Would be nice if text highlight annotation can be implemented in pdfsharp. I can't get the code in the accepted answer found on Stackoverflow to work: https://stackoverflow.com/questions/43413097/how-to-create-annotation-using-pdfsharp-to-highlight-text-of-existing-pdf. Not sure what I'm doing wrong. Here's my code using the PdfHighlightAnnotation class found on that site:

    public static void Main()
    {
        const string outName = "test1.pdf";
        PdfDocument? document = new PdfDocument();
        PdfPage? pageNewRenderer = document.AddPage();
        XGraphics? xgf = XGraphics.FromPdfPage(pageNewRenderer);

        xgf.DrawString("Hello world!", new XFont("Arial", 12), XBrushes.Black, 30, 30, XStringFormats.Default);

        PdfHighlightAnnotation highLightAnnot = new PdfHighlightAnnotation();
        highLightAnnot.Title = "Title";
        highLightAnnot.Subject = "Subject";
        highLightAnnot.Contents = "Contents";   
        highLightAnnot.Opacity = 1.0;

        var rect = xgf.Transformer.WorldToDefaultPage(new XRect(new XPoint(30, 30), new XSize(100, 20)));
        highLightAnnot.Rectangle = new PdfRectangle(rect);
        highLightAnnot.Color = XColors.Yellow;

        pageNewRenderer.Annotations.Add(highLightAnnot);
        SaveDocument(document, outName);
    }