How to read or calculate pdf page margins

92 Views Asked by At

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.

  1. comparing MediaBox & TrimBox.
  2. 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;
    }

second question;

Is there a way to iterate through all elements in the pdf page and find their rendering positions to find the distance between page and the elements ?

something like;

 public void IteratePdfElements(string pdfFilePath)
 {
     // Get the content of the page
     using PdfDocument pdfDocument = PdfReader.Open(pdfFilePath, PdfDocumentOpenMode.ReadOnly);

     PdfPage page = pdfDocument.Pages[0]; // Get the first page

     foreach (PdfItem? content in page.Contents.Elements)
     {
         PdfSharpCore.Pdf.Advanced.PdfReference pdfContent = (PdfSharpCore.Pdf.Advanced.PdfReference)content;

         Debug.WriteLine(content.ToString());

Thanks

0

There are 0 best solutions below