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

Setting column heights and spacing in Bootstrap

I'm looking to dynamically populate the blocks. Essentially, a for loop would be used to pass the data. However, I'm facing some challenges with the height of the blocks at different screen sizes while utilizing bootstrap 4. My goal is to have th ...

When applying animations to ngIf, the elements end up overlapping

I'm struggling to animate div elements when toggled using the Angular directive *ngIf. The issue I'm facing seems to be a common delay/timing problem in animations, but I haven't been able to find a solid solution. 1) When the current elem ...

Running system commands using javascript/jquery

I have been running NodeJS files in the terminal using node filename.js, but now I am wondering if it is possible to execute this command directly from a JavaScript/jQuery script within an HTML page. If so, how can I achieve this? ...

Implementing a horizontal scrollbar for an AJAX datatable

Is there a way to incorporate a horizontal scrollbar into an Ajax Datatable? I attempted to use "ScrollX" :true, however, this method did not prove successful. $(document).ready(function () { $('#myDataTable1').DataTable({ "aj ...

MUI useStyles/createStyles hook dilemma: Inconsistent styling across components, with styles failing to apply to some elements

I have been trying to style my MUI5 react app using the makeStyles and createStyles hooks. The root className is being styled perfectly, but I am facing an issue with styling the logoIcon. Despite multiple attempts to debug the problem, I have not been suc ...

PHP's $_SESSION variable for passing data between pages

Every time I visit a new page, whether it's a login page or any other, I want to store the name of that page in a $_SESSION variable. For example, on the login page: <?php session_start(); $_SESSION['page'] = 'login.htm&apo ...

Retrieving information from a web address is displaying unusual characters

Having trouble retrieving data from a JSON file using Java. When accessing the URL in a browser, the data displays correctly. However, when attempting to retrieve the data with Java, I am getting unreadable characters that cannot be parsed. This code works ...

What is the best way to input an HTML element into AngularJS code?

I am looking to integrate the html element into my angularjs code. Within my HTML, I have elements such as data-form-selector='#linechart_general_form' and data-url="{% url 'horizon:admin:metering:samples'%}" that I need to access withi ...

Issue encountered while attempting to create entity in jhipster

After executing the creation of an entity in the command line, JHipster successfully generated Java and script files but encountered issues with updating the database. No new table was inserted despite starting MySQL and turning off the application befor ...

Storing Unique Characters in the Database

Currently, I am utilizing a combination of HTML and PHP for my website, but I have encountered an issue when saving content in a textarea. Whenever I incorporate a different font with special characters like ' and ", it saves as � (a black dia ...

Selenium WebDriver Element does not exist, causing the condition to fail

In my script, there is a scenario where I have an If Else block nested within a while loop. The logic involves checking if an element is present - if it is, the program clicks on it to remove it from the parent list and then puts it back. If the element is ...

Is there a way to prevent elements from resizing when zooming in or out?

What is the best way to prevent elements from resizing on a standard website when users zoom in (CTRL +)? ...

Is there a way to assign retrieved data to the $scope.variable?

I'm relatively new to both JavaScript and Angular. I have a piece of code that fetches data from an API and successfully prints it to the console, but I'm facing issues when trying to assign this data to $scope.saveData. It seems to only work wit ...

Develop a circular carousel using React JS from scratch, without relying on any third-party library

I am looking to replicate the carousel feature seen on this website. I want to mimic the same functionality without relying on any external libraries. I have found several resources explaining how to achieve this. Most suggest creating duplicate copies o ...

What is the best way to align the bottom of an anchor element with the bottom of an SVG element when positioning them together

I am working on a test website where I am trying to create an interesting visual layout. My goal is to place an SVG image in the background, with an anchor element and other elements laid out above it. The challenge I am facing is aligning the bottom of th ...

Error encountered in main thread: org.openqa.selenium.WebDriverException - an unexpected error occurred: net::ERR_CONNECTION_CLOSED

I'm new to QA and I recently attempted to automate for the first time using Microsoft Edge Version 109.0.1518.61. Unfortunately, I encountered these errors: Here is the first error, and here is the second error. SLF4J: Failed to load class "org. ...

The link in the navigation bar is not functioning correctly

Let me break down the issue I'm facing here. The problem arises with the navigation buttons that have sub-lists nested within them (ul>li>ul). When attempting to click on these buttons, the link does not work unless I specifically click on the text it ...

When the caret triangle is upside down, it indicates that a drop-down menu is available even when the

I am facing an issue with a dropdown list where the triangle indicator is incorrectly displayed: https://i.stack.imgur.com/L4NBW.png Both images show that the arrows are in reverse direction, and I am struggling to identify the cause of this problem. He ...

What Could Be Causing My Webfonts to Be Inaccessible on Windows Devices and iPhones?

I recently created a simple holding page on www.tomrankinmusic.com The Webfonts I embedded in the page display correctly in the latest versions of Firefox, Safari, and Chrome on Mac OSX Lion 10.7.4 but do not show up in Chrome and IE6 on Windows XP Pro, d ...

Looking to extract latitude and longitude data using an Autocomplete Address Form

I am currently attempting to utilize Google Maps autocomplete feature in order to save latitude and longitude. Unfortunately, I am encountering difficulties in making this functionality work as intended. Given that I am unfamiliar with the Google Maps API, ...