Converting HTML and CSS to PDF in Java using iText

I've been working on converting HTML to PDF. Initially, I transformed my HTML code into XHTML using the resources provided in this link:

After successfully displaying the generated XHTML code in a browser by creating an HTML file for testing purposes, I proceeded to convert the HTML file to PDF using Java code.

public static final String DEST = "C:/Users/Turgut/Desktop/test12.pdf";
public static final String[] HTML = { "C:/Users/Turgut/Desktop/New Text Document (5).html", "C:/Users/Turgut/Desktop/New Text Document (5).html" };

public static void main(String[] args) {

    File file = new File(DEST);
    file.getParentFile().mkdirs();
    new TestHtmlToPdf().createPdf(DEST);
}

public void createPdf(String file) {
    Document document = new Document();
    try {
        //String HTML = "C:/Users/Turgut/Desktop/test12.html";
        PdfWriter.getInstance(document, new FileOutputStream(file));
        document.open();
        String css = readCSS();
        for (String htmlfile : HTML) {
            String html = Utilities.readFileToString(htmlfile);
            ElementList list = XMLWorkerHelper.parseToElementList(html, css);
            for (Element e : list) {
                document.add(e);
            }
            document.newPage();
        }
        document.close();
    }
    catch(IOException e) {
        e.printStackTrace();
    }
    catch(DocumentException ex) {
        ex.printStackTrace();
    }
}

private String readCSS() throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int length;
    InputStream is = XMLWorkerHelper.class.getResourceAsStream("/default.css");
    while ((length = is.read(buffer)) != -1) {
        baos.write(buffer, 0, length);
    }
    return new String(baos.toByteArray());
}

Included below is a style tag within the head tag:

<style type="text/css">
                body {
                background-color: #FFFFFF;
                font-family: 'Tahoma', "Times New Roman", Times, serif;
                font-size: 11px;
                color: #666666;
                }
                h1, h2 {
                padding-bottom: 3px;
                padding-top: 3px;
                margin-bottom: 5px;
                color : #000000;
                text-transform: uppercase;
                font-family: Arial, Helvetica, sans-serif;
                } 
                ...
                (Additional CSS styles)
                ...                    
                td {
                border-color:#000000; 
                }</style>

While I was able to generate the PDF file from the HTML file, it seems that there may be issues with reading the CSS block since there are discrepancies in text colors between the PDF and HTML files.

If anyone has suggestions on how to ensure CSS compatibility in generating the PDF file, I would greatly appreciate it. Thank you!

Answer №1

    FileInputStream htmlFile = new FileInputStream(new File(htmlSource));
    FileInputStream cssFile = new FileInputStream(new File(cssSource));
    htmlFile = getHtmlInputStream(); //this is just for my own reference
    // first step
    Document document = new Document();
    // second step
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(destPdf));
    writer.setInitialLeading(12);
    // third step
    document.open();

    // fourth step
    XMLWorkerHelper.getInstance().parseXHtml(writer, document, htmlFile, cssFile);

    // fifth step
    document.close();

This is my process.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for achieving jQuery form submission with Ajax functionality

Currently in my Java application, I am submitting a form using JQuery. Below is the JSP code snippet: <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> ...

Insert metadata tag into the head element of the parent iframe

I am looking to insert a meta tag element into the head element of an Iframe parent. I attempted window.parent.$('head').append('sometext'); This method worked when the source file and iframe file were in the same folder, however it d ...

Randomly alter the items displayed in list view

When utilizing a listview and changing the value of an item by clicking on the plus button, everything works smoothly until the user scrolls down and displays more items. It appears that the value of the item changes on each scroll page! I am unsure why ev ...

Implement a dialog on top of a current web page, achieve php-ajax query result, and enhance with

My website features 'dynamic' content, where 'static' nav-buttons replace specific div contents upon clicking. While I am able to retrieve my php/ajax results in a dialog box, I am struggling with placing this dialog above my current p ...

Reducing Image Size for Logo Placement in Menu Bar

Hello all, I am a newcomer to the world of web coding. Please bear with me if I ask something that may seem silly or trivial. I recently created a menu bar at the top of my webpage. Below that, there is a Div element containing an image. My goal is to make ...

Issue with Jquery focus on dropdown not working

I am facing an issue with setting up the dropdown feature for my list. It's similar to ul li:hover ul li. What I'm trying to achieve is something like ul li:focus ul li in jQuery because I don't think it can be done using CSS. The desired ou ...

Are you searching for a stylish tabbed navigation menu design?

I am searching for a tabbed navigation menu specifically designed to showcase images as the tab items. Here is an example of what I have in mind: <div class="menu"> <a href="#"> <img src="images/Chrysanth ...

Ways to terminate a process initiated through exec in Java: {.exec("cmd /c"+command)}

Recently, I initiated a Java process using the exec method in the Runtime class. The code snippet that illustrates this is shown below: Runtime r=Runtime.getRuntime(); Process p=null; String s="E:\\Softwares\\fiddler4setup.exe"; p=r ...

Is there a way to incorporate the ::after or ::before pseudo-elements into an image tag?

While working on my project, I attempted to incorporate the ::after tag (I had used ::before as well) for an image within an img tag. However, I am facing difficulties as it doesn't seem to be working. Any advice or guidance would be greatly appreciat ...

"Why does adding a new span create space between it and the previous ones, and what can be done to prevent this from

Essentially, it creates the equation "a + b = c". However, I need to create "a + b = c" instead. HTML: <div class="container"> <span id="b__value">+b</span> <span id="c__value">=c</span> &l ...

Upon the page loading, only select a handful of checkboxes (JSF)

I am currently developing a web application using JSF 2.0 and I need to have checkboxes pre-selected when the page loads. <h:selectManyCheckbox value="#{UserRegistration.rightSelected}" id="myRight"> <f:selectItem itemValue="add" itemLabel="A ...

Create dynamic flex transitions

After searching through various CSS resources and websites, I haven't found an answer to my specific query. I have been exploring CSS tricks as well as http://n12v.com/css-transition-to-from-auto/ but still uncertain if what I'm looking to achiev ...

What is the best way to manage selected checkboxes in PHP?

Could you please assist me with a problem I am facing? I have a form where users can select checkboxes, but I'm struggling to display the selected checkbox item names in the result. Currently, my HTML site is using the value attribute to calculate the ...

Steer clear of altering line spacing in CSS

Here is the HTML structure that I am working with: <div id="id1"> <h1>my name </h1><h3><a href="mailto:myemail_id"><a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ff92869a929e9693969bbf878685d19 ...

Creating HTML within a Servlet by incorporating additional quotation marks

Currently, I'm attempting to construct some HTML markup within a Spring controller. Here is a snippet of the code: append(sb ,"<div class=&quot;myDiv&quot;>"); This code snippet ends up generating the following HTML source in the brows ...

Trouble with jQuery delay in updating the CSS attribute while using fadeIn

After writing a simple JQuery code, I noticed that every time I click on 'eat', the animation lags. Is there any way to preload this animation for smoother performance? The #custom_menu element is a full-page section with a fixed position (simil ...

Adjusting the array when items in the multi-select dropdown are changed (selected or unselected)

I am looking to create a multi-select dropdown in Angular where the selected values are displayed as chip tags. Users should be able to unselect a value by clicking on the 'X' sign next to the chip tag, removing it from the selection. <searcha ...

Tips on how to stop a webpage from scrolling and instead allow only the inner content to scroll

Check out my plunker for reference. The goal I am aiming for is as follows: The webpage should stay fixed and not scroll in any direction If the content overflows its container, a scroll bar should appear strictly within that container I have a main co ...

IE has trouble with CSS inline-block and width-auto styling, leading to incorrect rendering

Recently, I've noticed a strange behavior in Internet Explorer 9-11 and Edge (Spartan). In all browsers except for IE, my example displays as desired: However, in Internet Explorer, it looks different: I used to encounter this issue on multiple bro ...

my divs are not being affected by the max-width property and are retaining their

I've been learning CSS and HTML through an interesting tutorial on Udacity. Here's the code I've been working on: .image{ max-width: 50%; } .app{ display: flex; } .description{ color: red; max-width: 705px; } <h1 class="title" ...