Warm tip: This article is reproduced from serverfault.com, please click

How to split PDF files from A4 size to letter size (half of A4 size) C# with Itext library

发布于 2020-11-29 02:38:01

I want to split a pdf file from A4 size to letter size in c# Now i'm split it with this code , but it remains the same size

        string inPDF = Application.StartupPath + "\\log\\input.pdf";
        string outPDF = Application.StartupPath + "\\log\\output.pdf";\
        PdfStream pdfStream = new PdfStream(inPDF, FileMode.Open);
        PdfStream newPdfStream = new PdfStream(outPDF, FileMode.Create);
        PdfReader reader = new PdfReader(pdfStream);
        PageSize = reader.getPageSize(1);
        Document document = new Document(PageSize);
        PdfWriter writer = PdfWriter.getInstance(document, newPdfStream);
        document.open();
        PdfContentByte content = writer.Directcontent();
        PdfImportPage page = writer.getImportPage(reader, 1);
        content.addTemplate(page , 0 , 0);
        content.Fill();
        document.setPageSize(PageSize);
        document.Close();
        reader.Close();
  • This is the original pdf file enter image description here

  • This is Output Pdf file expecte enter image description here

How can I split pdf file to small size with half of A4 size ??? Thank for read my post !

Questioner
Bình Chu
Viewed
11
Bình Chu 2020-11-30 10:39:40

I fixed it with this code :

       FileStream newPdfStream = new FileStream(destineFile, FileMode.Create, FileAccess.ReadWrite);
        PdfReader reader = new PdfReader(sourceFile);
        iTextSharp.text.Rectangle pageSize = new iTextSharp.text.Rectangle(
            reader.GetPageSize(1).Width,
            (reader.GetPageSize(1).Height - reader.GetPageSize(1).Height * 2 / 3));
        Document document = new Document(pageSize);
        PdfWriter writer = PdfWriter.GetInstance(document, newPdfStream);
        document.Open();
        PdfContentByte content = writer.DirectContent;
        PdfImportedPage page = writer.GetImportedPage(reader, 1);
        content.AddTemplate(page, 0, -reader.GetPageSize(1).Height * 2 / 3);
        content.SetColorFill(BaseColor.WHITE);
        content.Fill();
        document.SetPageSize(pageSize);
        document.NewPage();

Now it worked well . You can adjust the file size in the pageSize variable. Good luck !