changing web pages into PDF format

I need to convert HTML to PDF on a Linux system and integrate this functionality into a web application. Can you suggest any tools that are capable of doing this? Are there any other tools I should consider for this task?

So far, I have attempted the following:

    html2ps htmlfilename > a.ps
    ps2pdf a.ps > a.pdf

However, this method does not handle images properly and ignores CSS styles. My development environment is Linux (RHEL5).

I also tried using , but encountered the following error:

  [root@localhost bin]# ./wkhtmltopdf www.example.com a.pdf
  ./wkhtmltopdf: error while loading shared libraries: libQtWebKit.so.4: cannot open shared object file: No such file or directory

Answer №1

Following the right direction: wkhtmltopdf is the most straightforward solution for this task. Keep in mind that the code available in repositories could be outdated (uncertain about the current state of this package); you might have to compile it from source or opt for the statically-linked version (which is substantial but comes with pre-included QT library and other dependencies).

In addition, in your scenario, it's possible that you're lacking a certain library - installing libqt4-webkit-dev could potentially resolve the issue.

Answer №2

There are a couple of simple and effective methods to convert HTML+CSS to PDF.

1) Utilizing the "Jspdf javascript" plugin with the "html2canvas plugin" (Web App).

  • Add the stable version of the jspdf plugin.

    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src ='https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.0.272/jspdf.min.js';
    document.head.appendChild(script);

  • Include the html2canvas plugin

    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js';
    document.head.appendChild(script);

  • Insert the following script

    var html2obj = html2canvas($('your div class here'));
    var queue  = html2obj.parse();
    var canvas = html2obj.render(queue);<br>
    var img = canvas.toDataURL("image/jpg");
    console.log(img);<br>
    var doc=new jsPDF("p", "mm", "a4");
    var width = doc.internal.pageSize.width;<br>
    var height = doc.internal.pageSize.height;
    doc.addImage(canvas, 'JPEG',  15, 35, 180, 240,'SLOW');
    doc.save("save.pdf");

  • Special instructions for IE 11

    document.getElementById("your div here").style.backgroundColor = "#FFFFFF";

2) Using wkhtmltopdf

  • Download and install wkhtmltopdf from here

  • wkhtmltopdf can be used directly from terminal/commandLine. In Java, a wrapper is available for use.

  • Code example using wkhtmltopdf wrapper

    import com.github.jhonnymertz.wkhtmltopdf.wrapper.Pdf;
    import com.github.jhonnymertz.wkhtmltopdf.wrapper.page.PageType;
    import com.github.jhonnymertz.wkhtmltopdf.wrapper.params.Param;
    public class PofPortlet extends MVCPortlet {<br>
    @Override
    public void render(RenderRequest request , RenderResponse response) throws PortletException , IOException<br>
    { super.render(request, response);
    Pdf pdf = new Pdf();<br>
    pdf.addPage("http://www.google.com", PageType.url);
    // Add a Table of contents
    pdf.addToc();
    // The "wkhtmltopdf" shell command accepts different types of options such as global, page, headers and footers, and toc. Please see "wkhtmltopdf -H" for a full explanation.
    // All options are passed as array, for example:
    // Save the PDF
    try {
    pdf.saveAs("E:\\output.pdf");
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }

3) Other useful tools include phantom.js, itextpdf, grabz.it

Answer №3

If you want to save a webpage as a PDF, one of the simplest methods is to open the site in any modern browser and use the built-in "print" feature to generate a PDF file (assuming you have a PDF printer installed on your device). However, this approach may not be applicable in all situations, especially when using a web application. Nevertheless, it's worth giving it a try.

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

What could be causing the issue: Unable to locate or read the file: ./styles-variables?

I'm currently following a tutorial on how to create responsive layouts with Bootstrap 4 and Angular 6. You can find the tutorial here. I've reached a point where I need to import styles-variables.scss in my styles file, but I keep encountering t ...

Discovering the generic type from an optional parameter within a constructor

Looking to implement an optional parameter within a constructor, where the type is automatically determined based on the property's type. However, when no argument is provided, TypeScript defaults to the type "unknown" rather than inferring it as "und ...

A step-by-step guide on initializing and setting a cookie value with expiration

Below is the code I have added. Can someone please help me locate the bug? Here is the code snippet: $_SESSION['browser'] = session_id(); setcookie($expire, $_SESSION['browser'], time() + (60 * 1000), "/"); echo "Value is: " . $_COO ...

Begin by executing the initial commit task with Git through Gulp, followed by performing the

I am currently working on a project and I am trying to use gulp to commit and push to git. However, I am encountering an issue where the push task is not waiting for the commit task to complete before running... Can anyone assist me with this? I want to s ...

The order of items in MongoDB can be maintained when using the $in operator by integrating Async

It's common knowledge that using {$in: {_id: []}} in MongoDB doesn't maintain order. To address this issue, I am considering utilizing Async.js. Let's consider an example: const ids = [3,1,2]; // Initial ids retrieved from aggregation con ...

Guide to transferring a PHP variable from a loop and converting it into a JavaScript variable

I am having an issue with accessing specific row values in a while loop that displays data from a mysql table into a table. Each row has a button to send data via ajax to another PHP page for insertion into another table. However, since I am outside of the ...

What could be causing this issue where the call to my controller is not functioning properly?

Today, I am facing a challenge with implementing JavaScript code on my view in MVC4 project. Here is the snippet of code that's causing an issue: jQuery.ajax({ url: "/Object/GetMyObjects/", data: { __RequestVerificationToken: jQuery(" ...

Ways to update the value within an object in an array stored in a BehaviorSubject?

My initial data is: const menuItems = [{id: 1, active: false}, {id: 2, active: false}] public menuSubject$ = new BehaviorSubject<MenuItem[]>(menuItems); public menu$ = this.menuSubject$.asObservable(); I am attempting to update the element with ...

How to set up 'ng serve' command in Angular to automatically open a private browsing window?

I am looking for a way to open my project in an Incognito Mode browser without storing any cache. Is there a specific Angular CLI flag that can be included in the ng serve -o command or in the Angular CLI configuration file to enable opening a browser in ...

Buttons are misaligned and do not align on a straight line

Below is the code output: https://i.stack.imgur.com/avhUu.png I am attempting to enhance the symmetry of these buttons. The minus (-) button appears slightly smaller than the plus (+) button even though they have the same padding. I have experimented w ...

Steps for layering three images with distinct red, green, and blue components using HTML and CSS

Is it possible to overlay three versions of an image, each with red, green, and blue components, in order to recreate the original image using only HTML and CSS? I have tried this HTML setup: <div id="container"> <img class="color" id="red" ...

Why isn't my Enum functioning properly to display the colored background?

Why isn't the Background Color showing up when I pass in the BGColor Prop dynamically in my next.js + Tailwind app? I have tried passing in the prop for my component, but the color is not appearing. <Title title='This is HOME' descripti ...

Enable only the current week days on the multiple date picker feature

Can anyone recommend a date picker that only shows the current week and allows for multiple date selections by the user? I found this jsfiddle which limits the display to the current week, but it doesn't support selecting multiple dates. I attempted ...

The hover effect does not carry over to duplicated HTML

I successfully added a node, but I forgot to include the hover function of the node in my application. The hover function is not necessary, and I need it to work with ie8 compatibility. Here's my HTML: <div id="appendCell" style="color:green; colo ...

What is the best approach to managing numerous files?

I have a couple of .js files: main.js require("./randomEvent.js").begin("hey"); require("./randomEvent.js").begin("hi"); require("./randomEvent.js").begin("hello"); randomEvent.js var repeat = true; exports.begin = (uniqueString) => { while (repe ...

What is the proper way to insert a line break within a string in HTML code?

Trying to simplify my code, I've turned to using Nunjucks to pass a group of strings to a function that will then display them. This is what it looks like: {% macro DisplayStrings(strings) %} {% for item in strings %} <div>{{ item.strin ...

Halt the program's process until the ajax request has finished

Struggling with what seems like a common issue of the "Asynchronous Problem" and finding it difficult to find a solution. Currently, I am working on a custom bootstrap form wizard which functions as tabs/slideshow. Each step in the wizard is represented b ...

Issue with DIV height in Internet Explorer occurs only when application is accessed using server name

Encountering a unique issue specific to IE (confirmed in v8 and v9). When utilizing jquery to determine the height of a div: $('#sys_MainPage').height() In Chrome, Firefox, and when accessing using the IP address, this code returns around 26 ...

Route creation unsuccessful while attempting to both download a file and send a response message, resulting in the error "Headers cannot be set after they have been sent to the client."

I'm currently working on setting up a route that will allow users to download a file and receive a response message in the HTML. I attempted to use the download function from express JS, but encountered some issues. Here is the code I am using: route ...

Having trouble creating a PDF from HTML

Having trouble with generating PDFs using various libraries as I keep encountering the following error: Fatal Error: spawn UNKNOWN The code snippet looks like this: mammoth.convertToHtml({ path: './backend/common/template.docx' } ...