When creating a PDF from HTML using iText, the CSS styling is not applied

Even though I am able to generate a PDF from an HTML string, the issue is that it doesn't apply the CSS styles. How can I create a PDF with CSS styling? Please assist! I have already attempted using CSSResolver.

Below is my code snippet:

{String result = "failed";

try 
{
String html2 ="<html>"+.....+"</html>" ;
  long timemilli = System.currentTimeMillis();
            String filename = "EastAfriPack2014_Ticket_"+timemilli;
           String writePath = Global.PDF_SAVE_PATH + filename ; 
           System.out.println("----------writePath--------------"+ writePath);

            OutputStream file = new FileOutputStream(new File(writePath+".pdf"));
            Document document = new Document();
            PdfWriter writer = PdfWriter.getInstance(document, file);
            document.open();
            InputStream is = new ByteArrayInputStream(k.getBytes());

            CSSResolver cssResolver = XMLWorkerHelper.getInstance().getDefaultCssResolver(false);  
            cssResolver.addCss("table {color: red;  background-color: blue; } ", true);

            XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);
            document.close();
            file.close();
            System.out.println("pdf created");
            result = filename;
            return filename;
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }
    }

Answer №1

Your method doesn't seem to be effective. I attempted it previously as it appeared to be the most straightforward way to convert HTML to a PDF, but encountered the same issue.

There are two options: either include the styles inline using the style attribute for the table

or

utilize the HTML and CSS files separately by passing them to the HelperClass

XMLWorkerHelper.getInstance().parseXHtml(writer, document, 
                    new FileInputStream("myhtmlFile.html"), 
                    new FileInputStream("myCSSFile.css"));

The HTML part can also be an inputStream you created earlier in the code.

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

Is there a way to detect when a CSS background image has finished loading? Does an event trigger upon completion?

I am facing an issue with my sidebar widget where there is an image background in place. On top of this, I have a search input form but I don't want the input to display until the image has fully loaded. Is there a way to add a load event handler to ...

How can I connect a jQuery slider to dynamically update a div's content?

I am trying to update the content of a Message div based on the position of my slider. Since my slider only has 5 positions, I need to display 5 different messages depending on which position is selected. Does anyone know how to accomplish this? Here is t ...

What could be the reason for the mouseleave event not functioning properly?

I have a JSFiddle that is working perfectly. Check out my Fiddle here. In my code, I am trying to make a div change colors when hovered over and then back to its original color when the mouse moves out. It works fine on JSFiddle but not locally. When I r ...

Executing two jQuery scripts simultaneously on one page

Struggling to use 2 jQuery objects simultaneously on the same page. Can't get them both working at once despite playing around with the code. I'm new to this, so any help would be greatly appreciated. The code in the head section looks like this ...

Can you increase all px measurements in Notepad++ by a factor of X?

Looking for help with a large HTML image map that contains over 3000 lines of images with specific top/left pixel positions. I'd like to replace these images with larger ones, which would require increasing all the pixel references by a certain amount ...

Enhance the <div> with interactive content through dynamic updates on click within the same element

I am currently developing an Editor-Menu for a website administration. When I open admin.php, the Editor-Menu should be loaded into the #ausgabe div using the code $('#ausgabe').load('./admin-ajax/ajax2.php'). This functionality is work ...

Add a touch of mystery to a triangle SVG with CSS shadows

Is there a way to apply shadows to SVG images, like a triangle? I've tried using polyfill solutions but they didn't give me the desired effect. Check out this JSFiddle where I showcase what I'm trying to achieve. This is my HTML: <div c ...

translating creates vacant spaces on both sides

I am working with a <div class="scrollable"> that has the CSS property overflow: scroll;. Additionally, I have another <div class="line1"></div> which should not trigger any scrolling on the <div class="scrolla ...

AngularJS - varying actions based on which input field I interacted with first

Here is the tutorial I referenced for this code: <!DOCTYPE html> <html> <head> <title>AngularJS Tutorials</title> <link rel="stylesheet" href="vendor/foundation/foundation.min.css"> </head> <body> & ...

What is the best way to match my JSON data to a POJO based on the JSON values?

After creating a Java POJO class from an XSD file using JAXB, I now have JSON data. How can I efficiently map my JSON values to the corresponding attributes in the POJO class? Any suggestions would be much appreciated. Thanks! ...

The default theme has not been specified in Tailwind CSS

During my recent project, I utilized React, Next.js in combination with Tailwind CSS. In this project, I delved into styling customization by implementing react-slick for a specialized slider. To achieve the desired aesthetic, I made modifications to the r ...

Each block in Svelte includes a unique shorthand attribute

I have a JSON variable that holds attributes in a specific structure: // This json variable defines the attributes for elements to be created let myElements = [ { attr1: "myAttr1", attr2: "myAttr2", }, { ...

How to centrally align text in list items using Bootstrap 5

Incorporating Bootstrap 5 into my project, I am facing a challenge with vertically aligning text in an li element. Despite trying various techniques mentioned in the Bootstrap documentation for middle/center alignment, none of them seem to be effective. I ...

When resizing the browser, the divs stack neatly without overlapping

We need to ensure that the 4 divs stack on top of each other without overlapping! The header should have the same width as the footer, 100% The menu should stack with the header and footer The content should be centered on the page and stack with the oth ...

Concealed scrollbar only visible upon resizing the page

For my personal project, I was in need of a custom scrollbar plugin with basic inertia effects and custom images. After some research, I decided to go with mCustomScrollbar. The documentation provided was quite clear, and implementing the script was troub ...

The most efficient way to retrieve values from a hashmap

I'm working with a hashmap that contains a large number of values. My goal is to check if it contains a specific key Id (from a list) and if it does, then execute a method on that object. Which approach would be preferable? for (int id : myList) { ...

The alignment of the table header and body becomes misaligned when attempting to freeze the header

I am currently working on making the header visible while scrolling down the page. I managed to achieve this by using display:block; in the CSS for the body element. However, I am facing an issue where the columns of the header are not aligned with the ...

How can I apply bold styling to primary nodes in jsTree using CSS?

I am currently utilizing the in conjunction with asp.net mvc. My objective is to apply bold styling to the text using CSS within the main nodes, specifically those with arrows (refer to the image below). https://i.sstatic.net/xg3uF.png Below is the code ...

What is the maximum number of files that FileUploader can accept when multi-select is enabled?

I encountered the following issue: A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll Additional information: Maximum request length exceeded. while attempting to upload 250 JPEG files, each around 98 KB in ...

Issue with z-index not applying to a fixed header

I've been attempting to recreate the problem using this plunker. .demo-blog.mdl-layout .mdl-layout__content { padding-top: 0px; position: relative; margin-top: -80px; z-index: 100; } header.main-header{ z-index: -50; } My goal is ...