danfickle / openhtmltopdf

An HTML to PDF library for the JVM. Based on Flying Saucer and Apache PDF-BOX 2. With SVG image support. Now also with accessible PDF support (WCAG, Section 508, PDF/UA)!
https://danfickle.github.io/pdf-templates/index.html
Other
1.9k stars 355 forks source link

How to auto scale PDF to fit A4 page #578

Open abozanona opened 3 years ago

abozanona commented 3 years ago

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 commented 3 years ago

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?

danfickle commented 3 years ago

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.

Taschi120 commented 2 years ago

Has there been any progress on this issue?

CFCEN commented 2 years ago

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

yasarutkuu commented 1 year ago

any update?

yaphet17 commented 2 months ago

@danfickle Any update on this?

DavidShuYi commented 2 weeks ago

@danfickle Any update on this?

you can use like this:

builder.useDefaultPageSize(263.1f, 372, PdfRendererBuilder.PageSizeUnits.MM);

You can set the height and width of the scale equally, keeping the scale equal to 1.41, and preview the pdf file to see the effect.

372/263.1 = 1.4139...