crop Left side of pdf using Itextsharp

泄露秘密 提交于 2019-12-02 11:09:39

Making the hint in the comments an actual answer...

You create the new crop box rectangle like this:

PdfRectangle rectLeftside = new PdfRectangle(0,0,width - widthTo_Trim, height);

The constructor in question is:

/**
 * Constructs a <CODE>PdfRectangle</CODE>-object.
 *
 * @param       llx         lower left x
 * @param       lly         lower left y
 * @param       urx         upper right x
 * @param       ury         upper right y
 */
...
public PdfRectangle(float llx, float lly, float urx, float ury)

Thus, assuming your original PDF has a crop box with lower left coordinates (0,0), your code manipulates the upper right x, i.e. the right side of the box. You, on the other hand, actually want to manipulate the left side. Thus, you should use something like:

PdfRectangle rectLeftside = new PdfRectangle(widthTo_Trim, 0, width, height);

After the hint in comments, this also was the OP's solution.

Additional improvements

Using a PdfStamper

The OP uses a PdfSmartCopy instance and its method GetImportedPage to crop left side of pdf. While this already is better than the use of a plain PdfWriter for this task, the best choice for manipulating a single PDF usually is a PdfStamper: You don't have to copy anything anymore, you merely apply the changes. Furthermore the result internally is more like the original.

Determining boxes page by page

The OP in his code assumes

  1. a constant size of all pages in the PDF (which he determines in his methods GetPDFwidth and GetPDFHeight) and
  2. constant lower left coordinates (0,0) of the current crop box on all pages.

Neither of these assumptions is true for all PDFs. Thus, one should retrieve and manipulate the crop box of each page separately.

The code

public void TrimLeftImproved(string sourceFilePath, string outputFilePath)
{
    PdfReader pdfReader = new PdfReader(sourceFilePath);
    float widthTo_Trim = iTextSharp.text.Utilities.MillimetersToPoints(10);

    using (FileStream output = new FileStream(outputFilePath, FileMode.Create, FileAccess.Write))
    using (PdfStamper pdfStamper = new PdfStamper(pdfReader, output))
    {
        for (int page = 1; page <= pdfReader.NumberOfPages; page++)
        {
            Rectangle cropBox = pdfReader.GetCropBox(page);
            cropBox.Left += widthTo_Trim;
            pdfReader.GetPageN(page).Put(PdfName.CROPBOX, new PdfRectangle(cropBox));
        }
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!