openhtmltopdf icon indicating copy to clipboard operation
openhtmltopdf copied to clipboard

How to auto scale PDF to fit A4 page

Open abozanona opened this issue 5 years ago • 7 comments

I'm using Open HTML to PDF to generate PDF reports from simple html tables.

Sometimes, tables contain a big number of columns which overflows the right margin of the page.

I don't want to use cut-off solution. Instead, I'm trying to scale/resize the page content down to fit an A4 page size.

How can I dynamically scale down the content width to fit the page width?

abozanona avatar Oct 18 '20 09:10 abozanona

I wrote a code that loops through all document nodes and checks the max-width between all of them. And apply the scale later on the body tag.

private float getMaxWidth(Document doc) throws IOException {
    PdfRendererBuilder _builder = new PdfRendererBuilder();
    _builder.withW3cDocument(doc, url);
    PdfBoxRenderer _renderer = _builder.buildPdfRenderer();
    _renderer.layout();
    float maxWidth = getMaxWidth(_renderer.getRootBox());

    _renderer.getPdfDocument().close();
    _renderer.close();
    return maxWidth;
}

private float getMaxWidth(Box box) {
    float maxWidth = 0;
    maxWidth = Math.max(maxWidth, box.getWidth());
    for (int i = 0; i < box.getChildren().size(); i++) {
        maxWidth = Math.max(maxWidth, getMaxWidth(box.getChild(i)));
    }
    return maxWidth;
}


    doc = html5ParseDocumentFromHtml(html);

    float maxWidth = getMaxWidth(doc);
    float scale = 16320 / maxWidth;
    if(scale > 1){
        scale = 1;
    }
    html = html.replace("transform: none", "transform: scale(" + scale + ", 1)");
    doc = html5ParseDocumentFromHtml(html);

Is there a better way to do it?

abozanona avatar Oct 18 '20 12:10 abozanona

Hi @abozanona,

That might be the best way to achieve it currently, but we should be able to do this at the renderer phase, so leave this issue open.

danfickle avatar Oct 18 '20 14:10 danfickle

Has there been any progress on this issue?

Taschi120 avatar Aug 01 '22 15:08 Taschi120

You can use @page to customize the PDF size. When the HTML is created, set the HTML to A4 size, and then adjust the PDF size to fit the HTML content. Of course, you need to unmargin the PDF and set the HTML size to 595px by 842px

@page {

Size: 15.8 cm, 22.35 cm;

margin: 0cm;

} to HTML style, can achieve A4PDF conversion

CFCEN avatar Aug 20 '22 02:08 CFCEN

any update?

yasarutkuu avatar Nov 10 '22 14:11 yasarutkuu