使用itextshap从每个边缘裁剪Pdf

时间:2015-06-09 11:22:21

标签: c# pdf itext

我试图从每个边缘裁剪5毫米,即顶部,底部,右侧和左侧。我试过下面的代码

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

    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;
            cropBox.Right += widthTo_Trim;
            cropBox.Top += widthTo_Trim;
            cropBox.Bottom += widthTo_Trim;

            pdfReader.GetPageN(page).Put(PdfName.CROPBOX, new PdfRectangle(cropBox));
        }
    }
}

通过使用此代码,我只能裁剪底部部分。无法裁剪顶部和右侧 我怎样才能获得欲望结果?

1 个答案:

答案 0 :(得分:0)

这通过使用以下代码解决了我的问题

public void TrimLeftandRightFoall(string sourceFilePath, string outputFilePath, float cropwidth)
{
    PdfReader pdfReader = new PdfReader(sourceFilePath);
    float width = (float)GetPDFwidth(sourceFilePath);
    float height = (float)GetPDFHeight(sourceFilePath);
    float widthTo_Trim = iTextSharp.text.Utilities.MillimetersToPoints(cropwidth);

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

    using (var output = new FileStream(outputFilePath, FileMode.CreateNew, FileAccess.Write))
    {
        // Create a new document
        Document doc = new Document();

        // Make a copy of the document
        PdfSmartCopy smartCopy = new PdfSmartCopy(doc, output);

        // Open the newly created document
        doc.Open();

        // Loop through all pages of the source document
        for (int i = 1; i <= pdfReader.NumberOfPages; i++)
        {
            // Get a page
            var page = pdfReader.GetPageN(i);
            page.Put(PdfName.MEDIABOX, rectLeftside);

            var copiedPage = smartCopy.GetImportedPage(pdfReader, i);
            smartCopy.AddPage(copiedPage);
        }

        doc.Close();
    }
}