Search code examples
c#itext7

How to scale the page size from A3 to A4 in itext7 C #?


I tried to convert HTML to PDF at A4 page size. But the content is too long and PDF split into 2 pages. I just want it into one page. So my idea is convert to PDF A3 size, then scale down to A4 size. But another problem is scaling down from A3 page size to A4 page size.


Solution

  • 1) Convert your html to A3-sized document

    2) Iterate through pages and copy each page as a formXObject

    3) For each page formXObject:

    a) scale it with 0.5 coefficient;

    b) add to the resultant document.

    The appopriate Java code is as follows (there should be no problem for you to port it to C#, since the iText's API is just the same):

        // 1
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfDocument pdfDocument = new PdfDocument(new PdfWriter(baos));
        pdfDocument.setDefaultPageSize(PageSize.A3);
        HtmlConverter.convertToPdf(new FileInputStream(sourcePath), pdfDocument);
    
        PdfDocument resultantDocument = new PdfDocument(new PdfWriter(destPath));
    
        pdfDocument = new PdfDocument(new PdfReader(new ByteArrayInputStream(baos.toByteArray())));
        // 2
        for (int i = 1; i <= pdfDocument.getNumberOfPages(); i++) {
            PdfPage page = pdfDocument.getPage(i);
            PdfFormXObject formXObject = page.copyAsFormXObject(resultantDocument);
            PdfCanvas pdfCanvas = new PdfCanvas(resultantDocument.addNewPage());
            // 3a and 3b
            pdfCanvas.addXObject(formXObject, 0.5f, 0, 0, 0.5f, 0, 0);
        }
    
        pdfDocument.close();
        resultantDocument.close();