ststeiger / PdfSharpCore

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

Question; How to read or calculate pdf page margins? #386

Open devna13 opened 11 months ago

devna13 commented 11 months ago

Is there a way to calculate pdf margins for any given pdf ?

I tried few approaches via PdfSharpCore library and it didn't work for all pdfs.

comparing MediaBox & TrimBox. comparing MediaBox & Page. more info https://www.pdf2go.com/blog/what-are-pdf-boxes

    public Margins CalculateMargins(PdfPage page, PdfRectangle mediaBox, PdfRectangle trimBox)
    {
        // Didn't work; using Trim box (not being set for all pdfs) 
        //double leftMargin = XUnit.FromPoint( trimBox.X1 - mediaBox.X1).Inch; 
        //double topMargin = XUnit.FromPoint(trimBox.Y1 - mediaBox.Y1).Inch;
        //double rightMargin = trimBox.X2 > 0 ? XUnit.FromPoint(mediaBox.X2 - trimBox.X2).Inch : 0;
        //double bottomMargin = trimBox.Y2 > 0 ? XUnit.FromPoint(mediaBox.Y2 - trimBox.Y2).Inch : 0;

        //Didn't work; Calculate margins based on the page size and content size
        double leftMargin = XUnit.FromPoint(page.MediaBox.X1).Inch;
        double rightMargin = XUnit.FromPoint(page.MediaBox.Width - page.Width.Point).Inch;
        double topMargin = XUnit.FromPoint(page.MediaBox.Height - page.Height.Point).Inch;
        double bottomMargin = XUnit.FromPoint(page.MediaBox.Y2).Inch;

        this.PageMargins = new Margins(leftMargin, topMargin, rightMargin, bottomMargin);
        return PageMargins;
    }
tossnet commented 10 months ago

I don't found . Now I use this approche : https://github.com/ststeiger/PdfSharpCore/blob/master/docs/PdfSharpCore/samples/MultiplePages.md