pdfHTML: Responsive Design

Tags: pdfHtmlHTML to PDFiText7XMLWorkerXML Worker

A simple example that shows how pdfHTML can be used in conjuction with screen size mediaqueries and floating elements to create different PDFs using responsive webdesign.

Files: 
/*
    This file is part of the iText (R) project.
    Copyright (c) 1998-2017 iText Group NV
    Authors: iText Software.
 
    For more information, please contact iText Software at this address:
    sales@itextpdf.com
 */
package com.itextpdf.samples.pdfHTML.ResponsiveDesign;
 
import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.html2pdf.css.media.MediaDeviceDescription;
import com.itextpdf.html2pdf.css.media.MediaType;
import com.itextpdf.html2pdf.css.util.CssUtils;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.font.FontProvider;
import com.itextpdf.licensekey.LicenseKey;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
 
public class pdfHTMLResponsiveDesign {
 
    public static final String sourceFolder = "src/test/resources/pdfHTML/ResponsiveDesign/";
    public static final String destinationFolder = "target/output/pdfHTML/ResponsiveDesign/";
    public static final String[] files = {"responsive"};
 
    public static final PageSize[] pageSizes = {
            PageSize.A4.rotate(),
            new PageSize(720, PageSize.A4.getHeight()),
            new PageSize(PageSize.A5.getWidth(), PageSize.A4.getHeight())
    };
 
    //Path to the license file
    public static final String LICENSE = "src/test/resources/pdfHTML/itextkey-html2pdf_typography.xml";
 
    public static void main(String[] args) throws IOException, InterruptedException {
        LicenseKey.loadLicenseFile(LICENSE);
        for (String name : files) {
            String htmlSource = sourceFolder + name + "/" + name + ".html";
            String resourceFolder = sourceFolder + name + "/";
            String pdfDest = destinationFolder + name + "/" + name + ".pdf";
            File file = new File(pdfDest);
 
            System.out.println("Parsing: " + htmlSource);
            file.getParentFile().mkdirs();
            pdfHTMLResponsiveDesign runner = new pdfHTMLResponsiveDesign();
            //Create a pdf for each page size
            for (int i = 0; i < pageSizes.length; i++) {
                float width = CssUtils.parseAbsoluteLength("" + pageSizes[i].getWidth());
                String dest = destinationFolder + name + "/" + width + "/" + name + "_" + width + ".pdf";
                runner.parseMedia(htmlSource, dest, resourceFolder, pageSizes[i], width);
            }
 
        }
    }
 
    public void parseMedia(String htmlSource, String pdfDest, String resourceLoc, PageSize pageSize, float screenWidth) throws IOException {
        File pdf = new File(pdfDest);
        pdf.getParentFile().mkdirs();
 
        PdfWriter writer = new PdfWriter(pdfDest);
        PdfDocument pdfDoc = new PdfDocument(writer);
 
        //Set the result to be tagged
        pdfDoc.setTagged();
        pdfDoc.setDefaultPageSize(pageSize);
 
        ConverterProperties converterProperties = new ConverterProperties();
 
        //Set media device description details
        MediaDeviceDescription mediaDescription = new MediaDeviceDescription(MediaType.SCREEN);
        mediaDescription.setWidth(screenWidth);
        converterProperties.setMediaDeviceDescription(mediaDescription);
 
        FontProvider fp = new FontProvider();
        fp.addStandardPdfFonts();
        //Register external font directory
        fp.addDirectory(resourceLoc);
 
        converterProperties.setFontProvider(fp);
        converterProperties.setBaseUri(resourceLoc);
 
        //Create acroforms from text and button input fields
        converterProperties.setCreateAcroForm(true);
 
        HtmlConverter.convertToPdf(new FileInputStream(htmlSource), pdfDoc, converterProperties);
        pdfDoc.close();
    }
}
File nameRaw URLUpdated
pdfHTMLResponsiveDesign.javapdfHTMLResponsiveDesign.java2017-06-07 11:38 am
Resources: 
/*Actual Css*/
.dummy{
    /*Workaround to disable immediate flushing. With immediate flushing some form fields can throw up nullpointer exceptions*/
    /*Workaround needed for pdfHTML 1.0.0 and 1.0.1*/
    content:counter(pages)
}
p{
    margin-bottom: 5px;
    margin-left: 2px;
}
h2{
    color:#F9C227;
    margin: 0px;
}
[class*="col-"] {
    float: left;
}
.container{
    width:100%;
content: counters(pages);
}
.container::after{
    content: "";
    clear: both;
    display: table;
}
.header{
    background-color: #055587;
    color: #F9C227;
    margin-bottom:10px;
    /*width:100%;*/
}
 
.menu ul {
    list-style-type: none;
    margin-right: 10px;
    padding: 0;
}
.menu li {
    padding: 8px;
 
    margin-bottom: 7px;
    background-color: #055587;
    color: #ffffff;
    box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
 
}
.menu li:hover {
    background-color: #0099cc;
}
 
.aside {
    margin-top: 10px;
    background-color: #055587;
    padding-top: 0px;
 
    color: #ffffff;
    text-align: center;
    font-size: 14px;
}
 
/*Dynamic sizing*/
[class*="col-"]{
    width: 100%;
}
/*Mobile*/
@media only screen{
 
    p{
        font-size: 24pt;
    }
 
    h1{
        font-size: 36pt;
    }
 
    h2{
        font-size:28pt
    }
}
 
/*Tablet*/
@media only screen and (min-width: 600px) {
    .col-1-m {width: 24.9%;}
    .col-2-m {width: 49.9%;}
    .col-3-m {width:74%}
    .col-4-m {width: 99%;}
    p{
        font-size: 16pt;
    }
 
    h1{
        font-size: 24pt;
    }
 
    h2{
        font-size:18pt
    }
}
/*Desktop*/
@media only screen and (min-width: 768px ) {
        .col-1 {width:24.9%;}
        .col-2 {width: 33.32%;}
        .col-3 {width: 49%;}
        .col-4 {width: 99%;}
        p{
            font-size: 12pt;
        }
        h1{
            font-size: 20pt;
        }
 
        h2{
            font-size:16pt
        }
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="responsive.css"/>
    <!-- Based on the reponsive design example found at https://www.w3schools.com/css/css_rwd_intro.asp -->
</head>
<body>
<div class="header">
    <h1>iText</h1>
</div>
<div class="container">
    <div class="one col-1-m col-1 menu">
        <ul>
            <li>The Platform</li>
            <li>The Library</li>
            <li>The Company</li>
        </ul>
    </div>
    <div class="two col-3-m col-3 ">
        <h1>The Library</h1>
        <p>iText is a software developer toolkit that allows users to integrate PDF functionalities within their
            applications, processes or products. </p>
    </div>
    <div class="three col-4-m col-1">
        <div class="aside">
            <h2>What?</h2>
            <p>iText is a software developer toolkit that allows users to integrate PDF functionalities within their
                applications</p>
            <h2>How?</h2>
            <p>By providing you with the tools to create and manipulate a pdf in your source code</p>
            <h2>Really?</h2>
            <p>Yes really! </p>
        </div>
    </div>
</div>
<div class="container">
    <h2 class="header">Some filler text</h2>
    <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent ex arcu, varius a lorem et, malesuada tempor
        massa. Aenean elementum rutrum risus vel ultrices. Suspendisse lacinia elit ac purus fringilla porta. Fusce
        feugiat metus eget metus accumsan porta. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices
        posuere cubilia Curae; In hac habitasse platea dictumst. Cras semper mi ullamcorper velit molestie tempus.
    </p>
    <p>
        Curabitur pulvinar tellus quis maximus tristique. Praesent id aliquet tellus. Quisque in ipsum ut metus sagittis
        sollicitudin et sit amet dolor. Maecenas vitae tempor felis. Proin convallis justo ac rutrum bibendum.
        Suspendisse malesuada tincidunt varius. Phasellus non malesuada magna. Phasellus iaculis hendrerit neque, sit
        amet elementum velit fringilla sit amet. Suspendisse risus nunc, hendrerit id laoreet eget, tempus ut sem. In
        hac habitasse platea dictumst. Aliquam erat volutpat. Maecenas iaculis augue a eros sagittis, ac lacinia metus
        faucibus.
    </p>
    <p>
        Aenean in bibendum justo. Curabitur et mi tempus nibh aliquam congue. Praesent venenatis est sit amet mauris
        egestas accumsan. Proin fringilla leo enim, sit amet euismod justo pellentesque ut. Etiam dignissim nulla id dui
        porta posuere. Etiam posuere pulvinar suscipit. Donec consectetur massa at posuere finibus. Cras sit amet enim
        commodo, molestie urna condimentum, vestibulum justo. Mauris viverra pulvinar ipsum, non sodales ligula maximus
        et. Mauris libero leo, ultricies sit amet est non, venenatis pellentesque urna. Vestibulum tincidunt mauris ac
        posuere laoreet. Vivamus consectetur nisl elit, id euismod neque scelerisque non. Praesent tincidunt malesuada
        tristique. Aliquam sed leo tincidunt tortor facilisis convallis. Donec quis aliquam velit.
    </p>
    <h2 class="header">Some small input forms</h2>
    <div class="container">
        <div class="col-1-m col-1">
            First name: <input type="text" name="FirstName" value="Leeroy"><br>
            Last name: <input type="text" name="LastName" value="Jenkins"><br>
        </div>
        <div class="col-1-m col-1">
            Occupation: <input type="text" name="Occupation" value="Paladin"><br>
            Hobbies: <input type="text" name="Hobbies" value="Dragon Hunting"><br>
        </div>
    </div>
</div>
</body>
</html>
File nameRaw URLUpdated
responsive.cssresponsive.css2017-06-07 12:06 pm
responsive.htmlresponsive.html2017-06-07 12:06 pm
Results: 
File nameRaw URLUpdated
responsive_315.0.pdfresponsive_315.0.pdf2017-06-07 12:10 pm
responsive_540.0.pdfresponsive_540.0.pdf2017-06-07 12:10 pm
responsive_631.5.pdfresponsive_631.5.pdf2017-06-07 12:10 pm