ststeiger/PdfSharpCore

Question; How to read or calculate pdf page margins?

devna13 opened this issue · 1 comments

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;
    }