Generate PDF with CSS and Images

How Can I add HTML And CSS Into PDF

Important:
Please note that this answer was written in 2009 and it might not be the most cost-effective solution today in 2019. Online alternatives are better today at this than they were back then.

Here are some online services that you can use:

  • PDFShift
  • Restpack
  • PDF Layer
  • DocRaptor
  • HTMLPDFAPI
  • HTML to PDF Rocket

Have a look at PrinceXML.

It's definitely the best HTML/CSS to PDF converter out there, although it's not free (But hey, your programming might not be free either, so if it saves you 10 hours of work, you're home free (since you also need to take into account that the alternative solutions will require you to setup a dedicated server with the right software)

Oh yeah, did I mention that this is the first (and probably only) HTML2PDF solution that does full ACID2 ?

PrinceXML Samples

Generate Pdf from Html string with image and css for android using itext

I have Fixed Pdf Generate Issue With Xml Worker class.

For overcome CSS issues i have create external css file and apply it with the html.

For ex.

InputStream is = new ByteArrayInputStream(aHtmlString.getBytes());
InputStream css = new ByteArrayInputStream(cssString.getBytes());

XMLWorkerHelper.getInstance().parseXHtml(writer, document, is, css);

For Image Display issue copy your image From assets folder to phones internal folder.

Add give your img tag to that folder image path.

For ex.

<img src="/storage/emulated/0/MyApp/Images/my_logo.jpg"/>

Use This methods for copy files from asset to folder.

 public static void listAssetFiles(String path,Context ctx,String folderPath) {

String [] list;
try {
list = ctx.getAssets().list(path);
if (list.length > 0) {
// This is a folder
for (String file : list) {

copyIntoFolder(file,ctx,path+"/",folderPath);
}
}
} catch (IOException e) {

}

}

public static void copyIntoFolder(String fileName, Context ctx, String filePath, String folderPath){
AssetManager assetManager = ctx.getAssets();
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filePath+fileName);
File outFile = new File(folderPath , fileName);
out = new FileOutputStream(outFile);
Utility.copyFile(in, out);
in.close();
// in = null;
out.flush();
out.close();
//out = null;
} catch(IOException e) {
Log.e("IOException", "copyIntoFolder: ",e );

}
}

Itext doesnt support all css properties below is a list of suported css properties, create your html according this supported css properties.

Css Support

Generate pdf from HTML in div using Javascript

jsPDF is able to use plugins. In order to enable it to print HTML, you have to include certain plugins and therefore have to do the following:

  1. Go to https://github.com/MrRio/jsPDF and download the latest Version.
  2. Include the following Scripts in your project:

    • jspdf.js
    • jspdf.plugin.from_html.js
    • jspdf.plugin.split_text_to_size.js
    • jspdf.plugin.standard_fonts_metrics.js

If you want to ignore certain elements, you have to mark them with an ID, which you can then ignore in a special element handler of jsPDF. Therefore your HTML should look like this:

<!DOCTYPE html>
<html>
<body>
<p id="ignorePDF">don't print this to pdf</p>
<div>
<p><font size="3" color="red">print this to pdf</font></p>
</div>
</body>
</html>

Then you use the following JavaScript code to open the created PDF in a PopUp:

var doc = new jsPDF();          
var elementHandler = {
'#ignorePDF': function (element, renderer) {
return true;
}
};
var source = window.document.getElementsByTagName("body")[0];
doc.fromHTML(
source,
15,
15,
{
'width': 180,'elementHandlers': elementHandler
});

doc.output("dataurlnewwindow");

For me this created a nice and tidy PDF that only included the line 'print this to pdf'.

Please note that the special element handlers only deal with IDs in the current version, which is also stated in a GitHub Issue. It states:

Because the matching is done against every element in the node tree, my desire was to make it as fast as possible. In that case, it meant "Only element IDs are matched" The element IDs are still done in jQuery style "#id", but it does not mean that all jQuery selectors are supported.

Therefore replacing '#ignorePDF' with class selectors like '.ignorePDF' did not work for me. Instead you will have to add the same handler for each and every element, which you want to ignore like:

var elementHandler = {
'#ignoreElement': function (element, renderer) {
return true;
},
'#anotherIdToBeIgnored': function (element, renderer) {
return true;
}
};

From the examples it is also stated that it is possible to select tags like 'a' or 'li'. That might be a little bit to unrestrictive for the most usecases though:

We support special element handlers. Register them with jQuery-style
ID selector for either ID or node name. ("#iAmID", "div", "span" etc.)
There is no support for any other type of selectors (class, of
compound) at this time.

One very important thing to add is that you lose all your style information (CSS). Luckily jsPDF is able to nicely format h1, h2, h3 etc., which was enough for my purposes. Additionally it will only print text within text nodes, which means that it will not print the values of textareas and the like. Example:

<body>
<ul>
<!-- This is printed as the element contains a textnode -->
<li>Print me!</li>
</ul>
<div>
<!-- This is not printed because jsPDF doesn't deal with the value attribute -->
<input type="textarea" value="Please print me, too!">
</div>
</body>

CSS and Image not showing in rendered pdf using html-pdf-node

That's because the HTML string is being passed to html-pdf-node, the other assets like images and CSS are not. html-pdf-node uses Puppeteer as a headless browser to render the web page before saving it as PDF, when it tries to resolve the assets it sends HTTP requests that just fail.

You have two options to solve this:

  • Create a standalone HTML file with inline CSS and images as data URLs
  • Open a web server so that the assets can be resolved without being embedded

The simplest option is the second one, here is a minimal example:

const express = require('express')
const html_to_pdf = require('html-pdf-node')
const ejs = require('ejs')
const fs = require('fs')
const path = require('path')

const app = express()
const port = 3000

const template = fs.readFileSync(path.resolve(__dirname, "./index.html"), 'utf8')
const content = ejs.render(template, { title: "Awesome title!" })
fs.writeFile(path.resolve(__dirname, "./public/index.html"), content, () => {
app.use(express.static('src/public'))

const server = app.listen(port, async () => {
const url = `http://localhost:${port}`
const options = { format: 'A4', path: 'output.pdf' }
const file = { url }
await html_to_pdf.generatePdf(file, options)

server.close()
})
})

I've created a working project here: https://github.com/Guerric-P/html-pdf-node-demo

Add background image to each PDF page generated using html-pdf

I found the solution for the problem:

Due to PhantomJS limitation, apparently I have to also add the images to the body and hide them using display: none;
Once that's done, the images will also show in the header/footer sections of html-pdf.

More detailed information can be found here: https://github.com/marcbachmann/node-html-pdf/issues/12

Convert Html to pdf with images

    $('#showPdf').click(function() {      var pdf = new jsPDF();        pdf.addHTML($("#divContent"), function() {     var blob = pdf.output("blob");        window.open(URL.createObjectURL(blob));      });    });$('#downloadPdf').click(function() {  var pdf = new jsPDF();    pdf.addHTML($("#divContent"), function() { pdf.save('pageContent.pdf');  });});   
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.debug.js"></script>    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>    <div id="divContent" style="background-color: white; padding:20px 25px">      <h3>SEA MINK</h3>      <p>The sea mink (Neovison macrodon) was a mammal from the eastern coast      of North America, in the family of weasels and otters in the order Carnivora.      The largest of the minks, it was hunted to extinction by fur traders before 1903,      when it was first given a species description. Some biologists classify it as a subspecies of the      American mink. Estimates of its size are speculative, based largely on skull fragments recovered       from Native American shell middens, and on tooth remains. Some information on its appearance and       habits was provided by fur traders and Native Americans. It may have been similar in behavior to      the American mink: it probably maintained home ranges, was polygynandrous, and had a similar diet,       supplemented by saltwater prey. Sea minks were commonly trapped along the coast of the Bay of      Fundy in the Gulf of Maine. Remains have been found along the New England coast, and there were r      egular reports of unusually large mink furs, probably sea mink, being collected from Nova Scotia</p>            <img  src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBwgHBgkIBwgKCgkLDRYPDQwMDRsUFRAWIB0iIiAdHx8kKDQsJCYxJx8fLT0tMTU3Ojo6Iys/RD84QzQ5OjcBCgoKDQwNGg8PGjclHyU3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3N//AABEIAGMAYwMBEQACEQEDEQH/xAAbAAEAAgMBAQAAAAAAAAAAAAAABAYBAwUCB//EADgQAAEDAwEGAgYKAgMAAAAAAAEAAgMEBREGEiExQVFhE3EUMmKBkbEHFSIjQlJygqHBkvAzssL/xAAbAQEAAQUBAAAAAAAAAAAAAAAAAwECBAUGB//EADERAAIBAwEECAYDAQEAAAAAAAABAgMEESEFBhIxFCJBUWFxgdETMqGxwfBCkeFSFf/aAAwDAQACEQMRAD8A+4oAgCAIAgCAIAgCAIAgCAIAgCAIAgItTcKWnf4ckw8TGfDaC52OuBvx3UFe5o28eKrJRXiVUW+RHN2H4KeT9xA/srT1N5LGD0bl5L3wSqhNmBdetO79rgo47z2beGpL0XuV6PM9tvFGCBO805POYbLf8vV92VtLbadpcvFKom+7k/6ZHKnKPNE8EHgVnlhlAEAQBAEAQHiWRkMTpZXtZGwFznOOA0DiSUBW57lV3Un0V8lJbzwkH2Zpx2/I3v6x9nny21d4VRbpW2r7+xeXf9vMyKdDOsjMMMcDNiFgY3OTjmep6nuuLq1q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nQ9mbP61efxJ/8AK5ev+v0ZbxVJ8lgtmldL0OmqaRtOZJ6uc7VTWTHMkzu56dvmd609/tGreSXFpFcorkiWFNQJt7ukVnt76qVpkeSGQwt9aaQ+qweZ+AyeSisrOpd1lSh2/Rd5dOaissnaKtM1vtzpq9zZK+qeZ6qRo3GR3EDsBho7AL1GhRhQpRpU1otDXNtvLLIpSgQBAEBy9QWWK9UjY3SOgqYX+LTVMfrwSDmOoxkEcCCQVHWowrQdOosplU2nlFco7lNDWNtd8iZSXPfsbJ+6qgPxROPHu0/ab3GCfPdqbFq2cnOCzDv7vP35GbTqqWj5nUWkJjD2te3Ze0Ob0IyFVSa1Qwa2U0EbtqOCJjurWAFXOrN82ymEbVYVIF4u9JaIGyVbnF8h2YYIm7UszvysaN5P8Dmsuzsa13U4KSz9l5ls5qKyzVp+wVtyuLL3qGMRysB9EogdptK08STwMhHE8uA559E2bs2nY0uGOrfN/vYYNSo5suwAAAA3LZEZlAEAQBAEBEudto7rSOpbhTR1EDiCWSDOCOBHQjkRvCo0msMHBfYLpbwfquvbVwAfZpriTtDoBMMnH6muO/itBebu2td8VPqPw1X9ezRNGvJc9TBdcozszWaqyOLoZIntPl9oH+AtDV3YvIvqOMvXH3ROriPaYM1aR93Zrg89MRt/7PCshu1fSeuF6+2R0iBg2/UNYdlnodsi3fePJqJSOY2RhrT3y7yW1td16cdbiefBafX/ABEcrh/xJ9m0rbrXUOrCJKu4PbsyVtU7blcOgPBrfZaAOy6ehQp0IfDpRwjHbbeWd0DHBSlAgCAIAgCAIAgCAIAgCAIAgCAIAgCAIAgCAIAgCAIAgCAIAgCA/9k="/>      </div>      <button id="showPdf">Generate PDF</button><button id="downloadPdf">Download PDF</button>


Related Topics



Leave a reply



Submit