iTextSharp - Creating header/margins results in inconsistent page coordinates

百般思念 提交于 2020-01-06 17:58:02

问题


Why does the following code affect a page's ability to find its top, bottom, right and left?

Before applying it, reader.GetCropBox(i).GetLeft(0) and reader.GetPageSize(i).GetLeft(0) return the far left point of every page in an assorted set. After applying it, GetLeft(0) is the far left on some pages and on others the left most point AFTER the margin ends.

I'm trying to create a header on any given set of preexisting pages (ie, create white space and then put text in it)

using (Stream stream = new FileStream(outputPdfPath2, System.IO.FileMode.Create))
    {
        using (PdfReader reader = new PdfReader(outputPdfPath))
        {
            using (PdfStamper stamper = new PdfStamper(reader, stream))
            {
                int n = reader.NumberOfPages;

                for (int i = 1; i <= n; i++)
                {
                    //iTextSharp.text.Rectangle size = reader.GetPageSize(i);
                    iTextSharp.text.Rectangle size = reader.GetCropBox(i);

                    //////////
                    // Create Margin
                    float marginTop = 160;
                    float marginBottom = 160;
                    float marginLeft = 160;
                    float marginRight = 160;

                    float width = size.Width + marginLeft + marginRight;  // 8.5f * 72;
                    float height = size.Height + marginTop + marginBottom; // 11f * 72;
                    float tolerance = 1f;

                    iTextSharp.text.Rectangle cropBox = reader.GetCropBox(i);
                    float widthToAdd = width - cropBox.Width;
                    float heightToAdd = height - cropBox.Height;
                    if (Math.Abs(widthToAdd) > tolerance || Math.Abs(heightToAdd) > tolerance) 
                    {
                        float[] newBoxValues = new float[] { 
                            cropBox.Left    - marginLeft,  // widthToAdd  / 2,
                            cropBox.Bottom  - marginBottom,// heightToAdd / 2,
                            cropBox.Right   + marginRight, // widthToAdd  / 2,
                            cropBox.Top     + marginTop    // heightToAdd / 2
                        };
                        PdfArray newBox = new PdfArray(newBoxValues);

                        PdfDictionary pDict = reader.GetPageN(i);
                        pDict.Put(PdfName.CROPBOX, newBox);
                        pDict.Put(PdfName.MEDIABOX, newBox);
                    }
                    //////////
                }   
            }
        }
    }     

The original code is borrowed from the answer given here: How to resize existing pdf page size

来源:https://stackoverflow.com/questions/43791781/itextsharp-creating-header-margins-results-in-inconsistent-page-coordinates

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!