Khilarian
Khilarian

Reputation: 249

How to set page orientation in itextpdf HtmlConverter

In database I store different html templates for pdf. Today client ask to add landscape oriented template.

Well, now conversion works incorrectly: the template is landscape and part of text out of page, because page is vertical oriented.

I used itextpdf and conversion from html to pdf looks like:

public static byte[] convertString(String htmlContent, boolean useDefaultStyles) throws IOException {
        log.debug("html {}", htmlContent == null? 0: htmlContent.length());
        byte[] bytes = new byte[0];
        if(Strings.isNullOrEmpty(htmlContent)){
            return bytes;
        }
        try{
            if(useDefaultStyles){
                htmlContent = htmlContent.replace(
                        "<head>",
                        "<head>\n<style type=\"text/css\">@page {\tsize: A4; margin: 0; }</style>"
                );
            }
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            HtmlConverter.convertToPdf(htmlContent, baos);
            bytes = baos.toByteArray();
        } catch(Exception e){
            log.error("Error converting html to pdf", e);
        }
        log.debug("html2pdf {}", bytes.length);
        return bytes;
    }

What I need to add to fix this problem?

Thanks in advance.

Upvotes: 0

Views: 668

Answers (1)

S_G
S_G

Reputation: 481

Can you please try the following code. baseUri is basically a path to the directory that contain resources files like images/CSS.

/**
 * Creates the PDF file.
 *
 * @param baseUri the base URI
 * @param src     the path to the source HTML file
 * @param dest    the path to the resulting PDF
 * @throws IOException signals that an I/O exception has occurred.
 */
public void createPdf(String baseUri, String src, String dest) throws IOException {
    PdfWriter writer = new PdfWriter(dest);
    PdfDocument pdf = new PdfDocument(writer);
    PageSize pageSize = PageSize.A4.rotate();
    pdf.setDefaultPageSize(pageSize);
    ConverterProperties properties = new ConverterProperties();
    properties.setBaseUri(baseUri);

    HtmlConverter.convertToPdf(new FileInputStream(src), pdf, properties);
}

Upvotes: 1

Related Questions