Giter Site home page Giter Site logo

java-wkhtmltopdf-wrapper's Introduction

Java WkHtmlToPdf Wrapper Build Release

A Java based wrapper for the wkhtmltopdf command line tool. As the name implies, it uses WebKit to convert HTML documents to PDFs.

Requirements

wkhtmltopdf must be installed and working on your system.

Wrapper project dependency

Make sure you have Java Wrapper dependency added to your project.

If you are using Gradle/Maven, see example below:

Gradle

In your build.gradle:

dependencies {
    compile 'com.github.jhonnymertz:java-wkhtmltopdf-wrapper:1.3.0-RELEASE'
}

Maven

In your pom.xml:

<dependency>
    <groupId>com.github.jhonnymertz</groupId>
    <artifactId>java-wkhtmltopdf-wrapper</artifactId>
    <version>1.3.0-RELEASE</version>
</dependency>

Usage and Examples

// Attempt to find the wkhtmltopdf command from OS path
String executable = WrapperConfig.findExecutable();

// Initialize with the command wrapper
// Customize the OS command to be called if needed
Pdf pdf = new Pdf(new WrapperConfig(executable));

// Add global params:
pdf.addParam(new Param("--no-footer-line"), new Param("--header-html", "file:///header.html"));
pdf.addParam(new Param("--enable-javascript"));
pdf.addParam(new Param("--javascript-delay", "2000"));

// Add pages
Page page1 = pdf.addPageFromString("<html><head><meta charset=\"utf-8\"></head><h1>Müller</h1></html>");
Page page2 = pdf.addPageFromUrl("http://www.google.com");

// Add per-page params
page1.addParam(new Param("--footer-center", "Page1Footer"));
page1.addParam(new Param("--exclude-from-outline"));
page2.addParam(new Param( "--header-center", "Page2HeaderOverride"));

// Add a Table of Contents and ToC params
TableOfContents toc = pdf.addToc();
toc.addParam(new Param("--footer-center", "TocFooter"));
toc.addParam(new Param("--xsl-style-sheet", "my_toc.xsl"));

// Save the PDF
pdf.saveAs("output.pdf");

wkhtmltopdf location and automatic retrieval attempt

Library provides a method to attempt to find the wkhtmltopdf executable from the OS path, or an exact location can be provided:

// Attempt to find the wkhtmltopdf command from OS path
String executable = WrapperConfig.findExecutable();

// Exact custom location
String executable = "/usr/local/bin/wkhtmltopdf";

final Pdf pdf = new Pdf(new WrapperConfig(executable));

Note: make sure the tool wkhtmltopdf is installed and in the OS path for the user currently running the Java application. Otherwise, library will not be able to find the wkhtmltopdf. To test if the command is visible, you may try which wkhtmltopdf (linux) or where wkhtmltopdf (windows) in the command line.

Global params vs. per-object params

wkhtmltopdf accepts different types of options such as global, page, headers and footers, and toc. Please see wkhtmltopdf -H for a full explanation. The library allows setting params globally and per-object, as follows.

final Pdf pdf = new Pdf(new WrapperConfig(WrapperConfig.findExecutable()));

// Adding global params
pdf.addParam(new Param("--header-center", "GlobalHeader"));

// Adding per-object params
TableOfContents toc = pdf.addToc();
toc.addParam(new Param("--footer-center", "TocFooter"));

Page page1 = pdf.addPageFromString("<html><head><meta charset=\"utf-8\"></head><h1>Page1</h1></html>");
page1.addParam(new Param("--footer-center", "Page1Footer"));
page1.addParam(new Param("--exclude-from-outline")); // removes from toc

Page page2 = pdf.addPageFromUrl("http://www.google.com");
page2.addParam(new Param( "--header-center", "Page2HeaderOverride")); // override global header

Page/object ordering and ToC positioning

The list of pages/objects in the document appear as the order in which pages/objects were added to the main pdf. Except by the ToC, which is always placed at the beginning of the document. However, you can change this by using the setAlwaysPutTocFirst(false).

final Pdf pdf = new Pdf(new WrapperConfig(WrapperConfig.findExecutable()));

pdf.addCoverFromString("<html><head><meta charset=\"utf-8\"></head><h1>CoverPage</h1></html>");
pdf.addPageFromString("<html><head><meta charset=\"utf-8\"></head><h2>Page 1</h2></html>");
pdf.addToc(); // ToC will be placed at the beginning of the document by default, regardless of the order of addition
pdf.addPageFromString("<html><head><meta charset=\"utf-8\"></head><h2>Page 2</h2></html>");

pdf.getPDF(); // ToC forced to go first, then in order of addition: cover, page 1 and page 2 

Changing ToC position

By default, the ToC is always placed at the beginning of the document. You can change this by using the setAlwaysPutTocFirst(false):

final WrapperConfig config = new WrapperConfig(WrapperConfig.findExecutable());
config.setAlwaysPutTocFirst(false);
final Pdf pdf = new Pdf(config);

pdf.addCoverFromString("<html><head><meta charset=\"utf-8\"></head><h1>CoverPage</h1></html>");
pdf.addPageFromString("<html><head><meta charset=\"utf-8\"></head><h2>Page 1</h2></html>");
pdf.addToc(); // ToC will be placed according to the order of addition as config.setAlwaysPutTocFirst(false) is set
pdf.addPageFromString("<html><head><meta charset=\"utf-8\"></head><h2>Page 2</h2></html>");

pdf.getPDF(); // Follows order of addition: cover, page 1, ToC, and page 2

Xvfb Support

XvfbConfig xc = new XvfbConfig();
xc.addParams(new Param("--auto-servernum"), new Param("--server-num=1"));

WrapperConfig wc = new WrapperConfig(WrapperConfig.findExecutable());
wc.setXvfbConfig(xc);

Pdf pdf = new Pdf(wc);
pdf.addPageFromUrl("http://www.google.com");

pdf.saveAs("output.pdf");

wkhtmltopdf exit codes

wkhtmltopdf may return non-zero exit codes to denote warnings, you can now set the Pdf object to allow this:

Pdf pdf = new Pdf();
pdf.addPageFromUrl("http://www.google.com");

pdf.setAllowMissingAssets();
// or:  
pdf.setSuccessValues(Arrays.asList(0, 1));

pdf.saveAs("output.pdf");

Timeouts

There are often situations in which the wkhtmltopdf may take longer to generate the file. By default, the library uses a 10 seconds timeout for all the internal processes depending on wkhtmltopdf. However, in some situation 10s may not be sufficient, thus you can customize this value:

Pdf pdf = new Pdf();
pdf.addPageFromUrl("http://www.google.com");

pdf.setTimeout(30); // 30 seconds timeout

pdf.saveAs("output.pdf");

Cleaning up temporary files

After the PDF generation, the library automatically cleans up the temporary files created. However, there may be situations in which the Pdf object is created but no PDF is generated. To avoid increasing the temp folder size and having problems, you can force the deletion of all temporary files created by the library by:

Pdf pdf = new Pdf();
pdf.cleanAllTempFiles();

This is not an official Wkhtmltopdf product

This library is not an official Wkhtmltopdf product. Support is available on a best-effort basis via github issue tracking. Pull requests are welcomed.

Known issues

Output of wkhtmltopdf is being added to resulting pdf (Issue #19)

  • Starting from 1.1.10-RELEASE version, there is a method saveAsDirect(String path), which executes wkhtmltopdf passing the path as output for wkhtmltopdf, instead of the standard input -. This saves the results directly to the specified file path without handling it with internal stdout.

Processes taking longer due to some wkhtmltopdf parameters, such as window.status, possibly resulting in timeouts (Pull #131)

  • Some parameters may cause wkhtmltopdf think that the page has not loaded and it will wait for longer, causing some internal processes of the library to be blocked. To avoid blocking the internal processes of the library, the given timeout (default 10s) was forcibly set to all the internal processes. This value can be increased by using setTimeout(int seconds). Please refer to the Timeouts section for more information.
  • This issue is often caused by developers unfamiliar with wkhtmltopdf features and not related to the library itself. If you are experiencing something related, check the command being generated and the parameters you are using. Try to remove them one by one to find the one causing the issue.

Because this library relies on wkhtmltopdf, it does not support concurrent PDF generations.

License

This project is available under MIT Licence.

java-wkhtmltopdf-wrapper's People

Contributors

a---- avatar arozak25 avatar billoneil avatar chbakouras avatar codewing avatar deepsourcebot avatar dependabot[bot] avatar evaldasu avatar evgenigordeev avatar jhonnymertz avatar madmuffin1 avatar northlarry avatar orencp avatar sschoeb avatar tomtasche avatar vrozkovec avatar wmcshane avatar xweiba avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

java-wkhtmltopdf-wrapper's Issues

Korean characters are not supported

Describe the bug
Korean Characters are not displaying as expected but rendered as a boxes.

To Reproduce
i am giving html as an input and when i open generated PDF then it does not show me Korean letter but a boxes.

Expected behavior
Korean character should be displayed
Environment (please complete the following information):

  • java-wkhtmltopdf-wrapper version:1. 1.10-RELEASE
  • wkhtmltopdf version: 0.0.1-SNAPSHOT

Additional context
My Html is : <meta charset="UTF-16">

유니코드에 대해 Test 유니코드

Problems with header and footers options if the parameters consist of spaces

When im trying to set the params as below
new Param("--replace", "headerTitle", "testing spaces parameters");

where i have a header.html setup
<span class="headerTitle"></span>

These errors shows up
Error: Failed to load http://parameters/, with network status code 3 and http status code 0 - Host parameters not found
Error: Failed loading page http://parameters (sometimes it will work just to ignore this error with --load-error-handling ignore)
Error: Failed to load http://spaces/, with network status code 3 and http status code 0 - Host spaces not found
Error: Failed loading page http://spaces (sometimes it will work just to ignore this error with --load-error-handling ignore)
Exit with code 1 due to network error: HostNotFoundError

it seems like the strings after the 1st word is recognised as http value.
and so i tried a standard param like
new Param("--footer-right", "Page [page] of [toPage]");
the same error occurs.
Can i get any help on this? ty.

Edited: Im running this on macOS High SIerra

Update org.apache.pdfbox:pdfbox to avoid vulnerability

In Apache PDFBox 1.8.0 to 1.8.15 and 2.0.0RC1 to 2.0.11, a carefully crafted PDF file can trigger an extremely long running computation when parsing the page tree. Check link.

We use this lib for testing, so it is better to upgrade org.apache.pdfbox:pdfbox to version 1.8.16 or later. For example:

org.apache.pdfbox pdfbox [1.8.16,)

pdfbox and junit dependency scope

should a scope of test be added for pdfbox and junit in the pom? i don't see either of these being used outside of unit tests and would not think they should be packaged with the project if that is the case. thanks!

stdout of wkhtmltopdf will be added to pdf

When running the following code on Linux, the standard output of wkhtmltopdf will be added to the created pdf. Without xvfb on Windows the created pdf is as expected.

Linux environment:
Ubuntu 14.04.3 LTS
wkhtmltopdf 0.12.2.1 (with patched qt)

Windows environment:
Windows 10
wkhtmltopdf 0.12.4 (with patched qt)

final XvfbConfig xc = new XvfbConfig();
xc.addParams(new Param("--auto-servernum"));

final WrapperConfig wc = new WrapperConfig();
wc.setXvfbConfig(xc);

Pdf pdf = new Pdf(wc);

pdf.addPage("http://...", PageType.url);

pdf.addParam(new Param("--orientation", "landscape"));

Files.copy(new ByteArrayInputStream(pdf.getPDF()), outputFile);

Created PDF

Loading pages (1/6)
[>                                                           ] 0%
[======>                                                     ] 10%
[=======>                                                    ] 12%
[==========>                                                 ] 17%
[=============>                                              ] 22%
[===============>                                            ] 25%
[================>                                           ] 27%
[=======================>                                    ] 39%
[=========================>                                  ] 42%
[==========================>                                 ] 44%
[============================>                               ] 47%
[=============================>                              ] 49%
[==============================>                             ] 50%
[==============================>                             ] 50%
[==============================================>             ] 78%
[=================================================>          ] 83%
[===================================================>        ] 86%
[============================================================] 100%
Counting pages (2/6)                                               
[============================================================] Object 1 of 1
Resolving links (4/6)                                                       
[============================================================] Object 1 of 1
Loading headers and footers (5/6)                                           
Printing pages (6/6)
[>                                                           ] Preparing
[>                                                           ] Page 1 of 60
%PDF-1.4
1 0 obj
<<
[...]

Error at Increased concurrency

Testing the code at high concurrency level (>27) gives the following error in rendering pdf from html,
Kindly do suggest for the same.
ERROR [2016-05-27 19:34:40,438] [dw-591 - GET /pdfrendrer?template=handlebar] [ ] io.dropwizard.jersey.errors.LoggingExceptionMapper: Error handling a request: 602402206e64b42b ! java.lang.RuntimeException: Process (xvfb-run --auto-servernum --server-num=1 /usr/bin/wkhtmltopdf - -) exited with status code 1: ! ! at br.eti.mertz.wkhtmltopdf.wrapper.Pdf.getPDF(Pdf.java:92) ! at br.eti.mertz.wkhtmltopdf.wrapper.Pdf.saveAs(Pdf.java:55) ! at dropwizard.RenderEngine.genHPdf(RenderEngine.java:103) ! at dropwizard.resources.HelloWorldResource.sayHello(HelloWorldResource.java:37) ! at sun.reflect.GeneratedMethodAccessor17.invoke(Unknown Source) ! at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ! at java.lang.reflect.Method.invoke(Method.java:497) ! at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81) ! at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144) ! at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161) ! at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$TypeOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:205) ! at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99) ! at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389) ! at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347) ! at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102) ! at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:326) ! at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271) ! at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267) ! at org.glassfish.jersey.internal.Errors.process(Errors.java:315) ! at org.glassfish.jersey.internal.Errors.process(Errors.java:297) ! at org.glassfish.jersey.internal.Errors.process(Errors.java:267) ! at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317) ! at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305) ! at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154) ! at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:471) ! at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:425) ! at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:383) ! at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:336) ! at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:223) ! at io.dropwizard.jetty.NonblockingServletHolder.handle(NonblockingServletHolder.java:49) ! at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1669) ! at org.eclipse.jetty.servlets.UserAgentFilter.doFilter(UserAgentFilter.java:83) ! at org.eclipse.jetty.servlets.GzipFilter.doFilter(GzipFilter.java:364) ! at io.dropwizard.jetty.BiDiGzipFilter.doFilter(BiDiGzipFilter.java:132) ! at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652) ! at io.dropwizard.servlets.ThreadNameFilter.doFilter(ThreadNameFilter.java:29) ! at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652) ! at io.dropwizard.jersey.filter.AllowedMethodsFilter.handle(AllowedMethodsFilter.java:43) ! at io.dropwizard.jersey.filter.AllowedMethodsFilter.doFilter(AllowedMethodsFilter.java:38) ! at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652) ! at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:585) ! at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1127) ! at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515) ! at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1061) ! at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141) ! at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97) ! at com.codahale.metrics.jetty9.InstrumentedHandler.handle(InstrumentedHandler.java:240) ! at io.dropwizard.jetty.RoutingHandler.handle(RoutingHandler.java:51) ! at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97) ! at org.eclipse.jetty.server.handler.RequestLogHandler.handle(RequestLogHandler.java:95) ! at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97) ! at org.eclipse.jetty.server.handler.StatisticsHandler.handle(StatisticsHandler.java:159) ! at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97) ! at org.eclipse.jetty.server.Server.handle(Server.java:499) ! at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:310) ! at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:257) ! at org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:540) ! at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:635) ! at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:555) ! at java.lang.Thread.run(Thread.java:745)

Publish to Maven Central

Would you consider pushing the releases to maven central and/or jcenter? It will be easier to consume downstream

429 too many requests error?

Hi - I'm currently getting this error when transferring a .jar file to our servers:

[ERROR] Could not transfer artifact com.github.jhonnymertz:java-wkhtmltopdf-wrapper:jar:1.0.2-RELEASE from/to jitpack.io (https://jitpack.io): Failed to transfer file: https://jitpack.io/com/github/jhonnymertz/java-wkhtmltopdf-wrapper/1.0.2-RELEASE/java-wkhtmltopdf-wrapper-1.0.2-RELEASE.jar. Return code is: 429 , ReasonPhrase:Too Many Requests. -> [Help 1]

Are there many requests going on at the moment? I haven't encountered this error before when deploying our instance.

Thanks for your help.

"Cannot run program "wkhtmltopdf" CreateProcess error=2, The system cannot find the file specified."

The error I have is in the title.
I looked into the code and ran the "where wkhtmltopdf" command myself and it returned the correct directory with the executable.
I'm running Windows 8.1
The bin directory is in my Path variable
The stack trace is the following:
at br.eti.mertz.wkhtmltopdf.wrapper.configurations.WrapperConfig.findExecutable(WrapperConfig.java:58) at br.eti.mertz.wkhtmltopdf.wrapper.configurations.WrapperConfig.<init>(WrapperConfig.java:18) at br.eti.mertz.wkhtmltopdf.wrapper.Pdf.<init>(Pdf.java:33)

The code I use is:
Pdf pdf = new Pdf(); pdf.addPage(dir + "HTML.HTML", PageType.file); pdf.addToc(); pdf.saveAs(dir + "PDF.pdf");
EDIT: A restart fixed it.

Implement a builder pattern to create Pdf

Problem: The usage of the library based on constructors is verbose and inefficient.

Solution: It would be nice to have builder pattern to create the Pdf and generate the command.

Can't get clickable links with wrapper

Describe the bug
For some reason simple html with default config (no config) produces unclickable link via wrapper.
At the same time direct run wkhtmltopdf test.html test.pdf produces clickable link.

To Reproduce

Pdf pdf = new Pdf();
pdf.addPageFromString("<html><body><a href='https://google.com'>GOGL</a></body></html>");
pdf.getPDF()

Expected behavior
Clickable link.

Environment (please complete the following information):

  • java-wkhtmltopdf-wrapper version: 1.1.14-release
  • wkhtmltopdf version: 0.12.6

Html and Pdf tmp-Files are not getting deleted

Hi,
i recently am using your wkhtmltopdf-wrapper for creating pdf files.
So far everything is fine, but since im creating a lot of files, my VM gets crowded by all the tmp.html and output.pdf files. I would like to delete those files after sending them. What do you think is the best way of dealing with this?
Thanks a lot.

Problems with Params

Hi,

I'm having trouble making the margin-top work, I tried doing the following:
// pdf.addParam (new Param ("- enable-javascript"));
// pdf.addParam (new Param ("-page-size", "A4"));
// pdf.addParam (new Param ("- margin-top", "53mm"));

or
pdf.addParam(new Param("--enable-javascript"), new Param("--page-size", "A4"), new Param("--margin-top", "53mm")););

And the text does not generate a margin at the top.

Then what I found strange is that I commented on these parameters above and gave the same result in the pdf generation.

But I tested at command-line and works fine.

Any idea? ou update I have todo?

wkhtmltopdf command was not found in your classpath

win10系统中已经将wkhtmltopdf路径加入到path中了,可以在cmd中使用wkhtmltopdf,但是还是提示wkhtmltopdf command was not found in your classpath. Verify its installation or initialize wrapper configurations with correct path/to/wkhtmltopdf

wkhtmltopdf --footer-* and --header-* parameters do not work

The wkhtmltopdf paramteres related to header and footer content do not work when there are space characters in the string, for example:

pdf.addParam(new Param("--footer-center", "foo bar"));

Will cause an error because the "foo bar" portion of the parameter is not properly escaped and wkhtmltopdf will read it as page source urls. Trying to wrap the parameter value with \" or ' was also unsuccesful.

The root cause of this is the way that command is built as a single string rather than an array of String for Runtime#exec(). I have forked the repository in order to apply this small patch, which you can see here: pauldub@03936f2 (ignore the logger which I used to debug some issues).

Would you like a PR for this?

accent error

Hi,

I use your lib like this :

try {
        String html = menuDisplay(orderNumber, documentType);

        Pdf pdf = new Pdf();
        pdf.addPage(html, PageType.htmlAsString);
        pdf.addParam(new Param("--no-footer-line"));

        return pdf.getPDF();
    } catch (Exception e) {
        throw new ServerException("Error pdf convertion", e);
    }

And the output result does not have accent, example

Maître d'hôtel (
€ 268,52 HT

Idea ?

Thanks for your lib and your respons

Missing per object options and ordering of objects

Is your feature request related to a problem? Please describe.
The wkhtmltopdf tool allows:

  • Specifying multiple objects and options for each
  • The order of these objects, for example:
    • cover, toc, page; or
    • page, page, toc, page

Example command that uses global options, per object options and specific order of objects:

wkhtmltopdf --header-font-size 10 \
cover cover.html \
page foreword.html --header-left "Foreword" \
toc \
page test.html --footer-right "[page] of [topage]" \
output.pdf

Format:

wkhtmltopdf <GlobalOptions> <[Object] [ObjectOptions]>... <Output>

Currently, i'm facing an issue where i have a document that has the following:

  • Cover Page
  • Amendments Page
  • Foreword Page
  • Table Of Contents Page
  • Document Content Page/s

The current wrapper always puts the table of contents first, removing the ability to specify where in the document it should be placed.
Additionally, the amendments and foreword shouldn't be included in the table of contents, however, the wrapper currently doesn't support per page parameters so specifying --exclude-from-outline for these pages only isn't possible.

Describe the solution you'd like
Update the following classes to have:
Page:

  • Support for various types (cover, page, toc)
  • Params object (allow for object specific params)

Pdf:

  • List of pages is the order in which objects are added to the final command
  • Remove tocParams and use page of type toc (allows specifying location of toc in final document).
  • Leave params to be used as global options

The above solution would allow the tool to generate more complicated documents and remove any issues resulting from seperate generations and merging pdfs (Broken bookmarks in this case, details below).

Describe alternatives you've considered
I have tried generating out parts of a pdf individually and then merging the resulting pdfs. However, this results in broken bookmark links that no longer link correctly from the table of contents to the content in the final pdf.

I have also tried only using the params list to achieve:

  • Custom ordering of objects
  • To prevent getCommandAsArray limitations of placing the toc first
  • Per object options

This does work, however, this is not as intuitive and requires manually writing pages to temp storage, as adding to the page list results in the page being added to the end of the final command and no way to specify commands to follow it.
Additionally, this feels a little hacky like I'm fighting or abusing the wrapper to achieve the desired output, rather than letting the wrapper do the heavy lifting and construction of the final command.

Additional context
I can provide more information or examples if needed. I have also got an implemented solution to the above, I will submit a PR shortly as this may help highlight what i'm trying to achieve.

Exit with code 1 due to network error: ConnectionRefusedError

Jul 26 13:59:01 ip-172-31-31-97 oms.jar[317062]: com.github.jhonnymertz.wkhtmltopdf.wrapper.exceptions.PDFExportException: Process (/usr/local/bin/wkhtmltopdf --margin-top 10 --margin-bottom 0 --margin-left 20 --margin-right 20 --enable-local-file-access --viewport-size 1920×1080 /tmp/java-wkhtmltopdf-wrapper24ad1ef4-dd81-4f36-85fb-37a2836d66628538789048534919579.html /upload/tmp/08cbe37d-f5f3-4e36-96bd-c5cb55222ed2_1627307939947.pdf) exited with status code 1:
Jul 26 13:59:01 ip-172-31-31-97 oms.jar[317062]: Loading pages (1/6)
Jul 26 13:59:01 ip-172-31-31-97 oms.jar[317062]: [361B blob data]
Jul 26 13:59:01 ip-172-31-31-97 oms.jar[317062]: [356B blob data]
Jul 26 13:59:01 ip-172-31-31-97 oms.jar[317062]: [98B blob data]
Jul 26 13:59:01 ip-172-31-31-97 oms.jar[317062]: [110B blob data]
Jul 26 13:59:01 ip-172-31-31-97 oms.jar[317062]: Printing pages (6/6)
Jul 26 13:59:01 ip-172-31-31-97 oms.jar[317062]: [152B blob data]
Jul 26 13:59:01 ip-172-31-31-97 oms.jar[317062]: Exit with code 1 due to network error: ConnectionRefusedError
Jul 26 13:59:01 ip-172-31-31-97 oms.jar[317062]: at com.github.jhonnymertz.wkhtmltopdf.wrapper.Pdf.getPDF(Pdf.java:218)
Jul 26 13:59:01 ip-172-31-31-97 officems.jar[317062]: at com.github.jhonnymertz.wkhtmltopdf.wrapper.Pdf.saveAsDirect(Pdf.java:189)

Environment:

  • java-wkhtmltopdf-wrapper version: 1.1.13
  • wkhtmltopdf version: 0.12.6
  • OS: Ubuntu 20.04.2 LTS (GNU/Linux 5.4.0-1045-aws x86_64)

1.0.1-RELEASE

Thanks for the merge. Can you make the release so it is accessible via jitpack?

Support image?

Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

Describe the solution you'd like
A clear and concise description of what you want to happen.

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

Additional context
Add any other context or screenshots about the feature request here.

Fix unit test warnings

Fix unit test warnings

Warning: /home/runner/work/java-wkhtmltopdf-wrapper/java-wkhtmltopdf-wrapper/src/test/java/com/github/jhonnymertz/wkhtmltopdf/wrapper/integration/PdfIntegrationTests.java: Some input files use or override a deprecated API.
Warning: /home/runner/work/java-wkhtmltopdf-wrapper/java-wkhtmltopdf-wrapper/src/test/java/com/github/jhonnymertz/wkhtmltopdf/wrapper/integration/PdfIntegrationTests.java: Recompile with -Xlint:deprecation for details.

Ability to accept custom wkhtmltopdf command

Is your feature request related to a problem? Please describe.
When we're running our application code locally and in remote servers we do not use locally installed wkhtmltopdf command line tool, but instead use docker image that has that tool.
The command we pass to the WrapperConfig looks like this docker container exec wam_wkhtmltopdf wkhtmltopdf, where wam_wkhtmltopdf refers to the container of docker image cs2ag/docker-wkhtmltopdf.

After this change it seems to be no longer working, since we're getting java.io.IOException: Cannot run program "docker container exec wam_wkhtmltopdf wkhtmltopdf": error=2, No such file or directory.

Here's the debugger comparison of Runtime.getRuntime().exec() call, comparing 1.1.4 (working) and 1.1.14 (not working):
image

Describe the solution you'd like
We would like to use this wrapper not only with locally installed wkhtmltopdf command line tool, but also with docker containers.

I was thinking about changes in WrapperConfig to maybe parse the wkhtmltopdfCommand and return array of strings instead of string. Then do commandLine.addAll(wrapperConfig.getWkhtmltopdfCommandAsArray());

Describe alternatives you've considered

  • We considered installing wkhtmltopdf locally for each developer, as well as in remote servers where our app is running, but this seems to defeat the purpose of why we're using docker.
  • The only real alternative we see right now is to use Mulesoft repository and pull 1.1.4 from there.
  • Use obsolete and often unstable nexus.pentaho repositories, which we've used before. There's a 1.1.4 version in there.
  • Open a PR to this repository with a suggested fix

Additional context
As of now our team was using a 1.1.4 version which was fetched from some obscure and unstable repository. We recently changed that and decided to use maven central repositories as much as possible. We did not find a 1.1.4 in there so we went with the latest version (1.1.14).

Doesn't export textarea and images

I have been trying to use this wrapper and it works for everything but <textarea> and <img>
Here is the HTML/JS I have to make sure it catches the change:
HTML:
<textarea style="height: 236px; width: 629px;" rows="3" onchange="setValue(event)"></textarea>

JS:
function setValue(evt) { var node = evt.target || evt.srcElement; node.setAttribute("value", node.value); }

And here is the Java to export to pdf:

protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, InterruptedException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { Pdf pdf = new Pdf(new WrapperConfig("C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe")); pdf.addPageFromString(request.getParameter("content")); pdf.addParam(new Param("--enable-javascript")); pdf.saveAs("E:\\Websites\\Rosebud\\appForm1.pdf"); } }

I haven't figured out a way to make sure the images come out on the other side.

Support multiple htmlAsString input files

wkhtmltopdf/wkhtmltopdf#1847

PdfService pdf = ...;
pdf.addPage(..., PageType.htmlAsString);
pdf.addPage(..., PageType.htmlAsString);
pdf.getPdf();

The exception happens the second time you try to close STDIN:

java.io.IOException: Stream Closed
        at java.io.FileOutputStream.writeBytes(Native Method) ~[na:1.8.0_45]
        at java.io.FileOutputStream.write(FileOutputStream.java:326) ~[na:1.8.0_45]
        at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82) ~[na:1.8.0_45]
        at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:140) ~[na:1.8.0_45]
        at java.io.FilterOutputStream.close(FilterOutputStream.java:158) ~[na:1.8.0_45]
        at br.eti.mertz.wkhtmltopdf.wrapper.Pdf.getPDF(Pdf.java:78) ~[pdf-service.jar!/:na]

I think it'd be nice if the Java wrapper noticed that there are multiple htmlAsString inputs, and created temporary files for them.

Command line size limitation

There's a finite amount of characters that can be used on the command line. This limit varies across systems and all but if a user adds too many pages, this can cause the process to fail or output unexpected results.

wkhtmltopdf seems to handle this issue by providing the --read-args-from-stdin parameters, with the following documentation:

Reading arguments from stdin:
  If you need to convert a lot of pages in a batch, and you feel that
  wkhtmltopdf is a bit too slow to start up, then you should try
  --read-args-from-stdin,

  When --read-args-from-stdin each line of input sent to wkhtmltopdf on stdin
  will act as a separate invocation of wkhtmltopdf, with the arguments specified
  on the given line combined with the arguments given to wkhtmltopdf

  For example one could do the following:

  echo "http://qt-project.org/doc/qt-4.8/qapplication.html qapplication.pdf" >> cmds
  echo "cover google.com http://en.wikipedia.org/wiki/Qt_(software) qt.pdf" >> cmds
  wkhtmltopdf --read-args-from-stdin --book < cmds

See there: https://wkhtmltopdf.org/usage/wkhtmltopdf.txt

Also, I wonder if it would be possible to “demonize” the process by never closing the stdin of wkhtmltopdf, printing/flushing a line whenever a PDF is required.

Mac: wkhtmltopdf command was not found in your classpath.

Describe the bug
When calling findExecutable the exception is thrown:

com.github.jhonnymertz.wkhtmltopdf.wrapper.exceptions.WkhtmltopdfConfigurationException: wkhtmltopdf command was not found in your classpath. Verify its installation or initialize wrapper configurations with correct path/to/wkhtmltopdf
	at com.github.jhonnymertz.wkhtmltopdf.wrapper.configurations.WrapperConfig.findExecutable(WrapperConfig.java:66) ~[java-wkhtmltopdf-wrapper-1.1.15-RELEASE.jar:?]
	Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException: 

Running 'which wkhtmltopdf' in my terminal yields the path:

t@h pdf % which wkhtmltopdf
/usr/local/bin/wkhtmltopdf

To Reproduce
Install wkhtmltopdf, install the wrapper, call findExecutable

Expected behavior
Excecutable is found

Environment (please complete the following information):

  • java-wkhtmltopdf-wrapper version: 1.1.15-RELEASE
  • wkhtmltopdf version: 0.12.6 (with patched qt)
  • MacOS 13.1

A "Full" Error Stream Blocks the wkhtmltopdf Process

In method Pdf.getPDF, a "full" error stream blocks the wkhtmltopdf process. By "full" I mean that the wkhtmltopdf stderr's buffer is full, causing wkhtmltopdf to block until the error stream is consumed, which will never happen. I fixed this by consuming the streams concurrently in separate Executors.

My Pdf.java:

package com.github.jhonnymertz.wkhtmltopdf.wrapper;

import com.github.jhonnymertz.wkhtmltopdf.wrapper.configurations.WrapperConfig;
import com.github.jhonnymertz.wkhtmltopdf.wrapper.page.Page;
import com.github.jhonnymertz.wkhtmltopdf.wrapper.page.PageType;
import com.github.jhonnymertz.wkhtmltopdf.wrapper.params.Param;
import com.github.jhonnymertz.wkhtmltopdf.wrapper.params.Params;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * Represents a Pdf file
 */
public class Pdf {

    private static final String STDINOUT = "-";

    private final WrapperConfig wrapperConfig;

    private final Params params;

    private final List<Page> pages;

    private boolean hasToc = false;

    public Pdf() {
        this(new WrapperConfig());
    }

    public Pdf(WrapperConfig wrapperConfig) {
        this.wrapperConfig = wrapperConfig;
        this.params = new Params();
        this.pages = new ArrayList<Page>();
    }

    /**
     * Add a page to the pdf
     *
     * @deprecated Use the specific type method to a better semantic
     */
    @Deprecated
    public void addPage(String source, PageType type) {
        this.pages.add(new Page(source, type));
    }

    /**
     * Add a page from an URL to the pdf
     */
    public void addPageFromUrl(String source) {
        this.pages.add(new Page(source, PageType.url));
    }

    /**
     * Add a page from a HTML-based string to the pdf
     */
    public void addPageFromString(String source) {
        this.pages.add(new Page(source, PageType.htmlAsString));
    }

    /**
     * Add a page from a file to the pdf
     */
    public void addPageFromFile(String source) {
        this.pages.add(new Page(source, PageType.file));
    }

    public void addToc() {
        this.hasToc = true;
    }

    public void addParam(Param param, Param... params) {
        this.params.add(param, params);
    }

    public File saveAs(String path) throws IOException, InterruptedException {
        File file = new File(path);
        FileUtils.writeByteArrayToFile(file, getPDF());
        return file;
    }

    public byte[] getPDF() throws IOException, InterruptedException {

        Future<byte[]> inputStreamToByteArray = null;
        Future<byte[]> errorStreamToByteArray = null;
        ExecutorService executor = Executors.newFixedThreadPool(2);

        try {
            Process process = Runtime.getRuntime().exec(getCommandAsArray());

            inputStreamToByteArray = executor.submit(streamToByteArrayTask(process.getInputStream()));
            errorStreamToByteArray = executor.submit(streamToByteArrayTask(process.getErrorStream()));

            process.waitFor();

            if (process.exitValue() != 0) {
                throw new RuntimeException("Process (" + getCommand() + ") exited with status code " + process.exitValue() + ":\n" + new String(getFuture(errorStreamToByteArray)));
            }

            return getFuture(inputStreamToByteArray);
        } finally {
            cancelFutures(inputStreamToByteArray, errorStreamToByteArray);
            cleanTempFiles();
        }
    }

    private String[] getCommandAsArray() throws IOException {
        List<String> commandLine = new ArrayList<String>();

        if (wrapperConfig.isXvfbEnabled())
            commandLine.addAll(wrapperConfig.getXvfbConfig().getCommandLine());

        commandLine.add(wrapperConfig.getWkhtmltopdfCommand());

        commandLine.addAll(params.getParamsAsStringList());

        if (hasToc)
            commandLine.add("toc");

        for (Page page : pages) {
            if (page.getType().equals(PageType.htmlAsString)) {

                File temp = File.createTempFile("java-wkhtmltopdf-wrapper" + UUID.randomUUID().toString(), ".html");
                FileUtils.writeStringToFile(temp, page.getSource(), "UTF-8");

                page.setSource(temp.getAbsolutePath());
            }

            commandLine.add(page.getSource());
        }
        commandLine.add(STDINOUT);
        return commandLine.toArray(new String[commandLine.size()]);
    }

    private Callable<byte[]> streamToByteArrayTask(final InputStream input) {
        return new Callable<byte[]>() {
            public byte[] call() throws Exception {
                return IOUtils.toByteArray(input);
            }
        };
    }

    private byte[] getFuture(Future<byte[]> future) {
        try {
            return future.get();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void cancelFutures(Future<?>... futures) {
        for (Future future: futures){
            if (future != null && !future.isDone()) {
                future.cancel(true);
            }
        }
    }

    private void cleanTempFiles() {
        for (Page page : pages) {
            if (page.getType().equals(PageType.htmlAsString)) {
                new File(page.getSource()).delete();
            }
        }
    }

    public String getCommand() throws IOException {
        return StringUtils.join(getCommandAsArray(), " ");
    }

}

Output and Error Stream data union

Hi, thanks for the wrapper, I used it as an example for writing an easier option for my needs. I encountered an error and did not have time to understand it. And so I decided just to warn you. Let's start with the fact that the wkhtmltopdf on my server just does not start for this reason: [https://github.com/wkhtmltopdf/wkhtmltopdf/issues/2037]. The solution was to use the wkhtmltopdf with the xvfb-run. It was necessary to change your source code for future use. You can track the changes in my repository. One problem has been resolved but there was another, for still unknown reason, the output stream is combined. data that should be in the console fell in the file. To avoid this, it was decided to abandon the error stream. I could not figure out the cause of the. But I think you can just keep it in mind.

addPageFromFile,How to use it????

Describe the bug
A clear and concise description of what the bug is.

To Reproduce
If possible, provide the steps to reproduce the behavior.

Expected behavior
A clear and concise description of what you expected to happen.

Environment (please complete the following information):

  • java-wkhtmltopdf-wrapper version:1.1.11
  • wkhtmltopdf version: 0.12.2

Additional context
Add any other context about the problem here.
image

Unknown long argument --javascript-delay 2000

I have a a page which is basically a single page vue component.

It doesn't render to pdf ( at all ) , shows a blank page. So i am trying to use the --javascript-delay 2000 param , to see if that will make a difference.

here is how i am trying to add that param.

pdf.addPageFromUrl("https://local.ncaa.org:8080/recruiting-calendar/");
pdf.addParam(new Param("--enable-javascript"));
pdf.addParam(new Param("--javascript-delay 2000"));

and this is what i am getting in the console output.

 c.g.jhonnymertz.wkhtmltopdf.wrapper.Pdf  : Initialized with {xvfbConfig=null, wkhtmltopdfCommand='/usr/local/bin/wkhtmltopdf'}
 c.g.jhonnymertz.wkhtmltopdf.wrapper.Pdf  : Command generated: [/usr/local/bin/wkhtmltopdf, --enable-javascript, --javascript-delay 2000, https://local.ncaa.org:8080/recruiting-calendar/, -]
c.g.jhonnymertz.wkhtmltopdf.wrapper.Pdf  : Generating pdf with: /usr/local/bin/wkhtmltopdf --enable-javascript --javascript-delay 2000 https://local.ncaa.org:8080/recruiting-calendar/ -
c.g.jhonnymertz.wkhtmltopdf.wrapper.Pdf  : Command generated: [/usr/local/bin/wkhtmltopdf, --enable-javascript, --javascript-delay 2000, https://local.ncaa.org:8080/recruiting-calendar/, -]
c.g.jhonnymertz.wkhtmltopdf.wrapper.Pdf  : Wkhtmltopdf output:
Unknown long argument --javascript-delay 2000

Lingering temporary html file

Environment

java version: openjdk 1.8.0_181
java-wkhtmltopdf-wrapper version: 1.1.9-RELEASE
wkhtmltopdf version: 0.12.5

Expected Behavior

Calling Pdf.saveAs() with html added via addPageFromString() cleans up all temporary files created to generate the pdf file.

Actual Behavior

Two java-wkhtmltopdf-wrapper*.html temporary files are created, but only one of them is cleaned up.

Likely Cause

In Pdf.getPDF() the command is logged on line 169 which requires a call to getCommand(). This calls getCommandAsArray() which creates a temporary file for every page.

When getCommandAsArray() is called on line 170, this creates yet another temporary file. cleanTempFiles() only cleans up one of these files, which leaves a lingering temporary html file.

Fix build warnings

There is a lot of missing javadocs:

[WARNING] Javadoc Warnings
[WARNING] /home/travis/build/[secure]/java-wkhtmltopdf-wrapper/src/main/java/com/github/[secure]/wkhtmltopdf/wrapper/Pdf.java:79: warning: no @param for source
[WARNING] public void addPage(String source, PageType type) {
[WARNING] ^
[WARNING] /home/travis/build/[secure]/java-wkhtmltopdf-wrapper/src/main/java/com/github/[secure]/wkhtmltopdf/wrapper/Pdf.java:79: warning: no @param for type
[WARNING] public void addPage(String source, PageType type) {
[WARNING] ^
[WARNING] /home/travis/build/[secure]/java-wkhtmltopdf-wrapper/src/main/java/com/github/[secure]/wkhtmltopdf/wrapper/Pdf.java:86: warning: no @param for source
[WARNING] public void addPageFromUrl(String source) {
[WARNING] ^
[WARNING] /home/travis/build/[secure]/java-wkhtmltopdf-wrapper/src/main/java/com/github/[secure]/wkhtmltopdf/wrapper/Pdf.java:93: warning: no @param for source
[WARNING] public void addPageFromString(String source) {
[WARNING] ^
[WARNING] /home/travis/build/[secure]/java-wkhtmltopdf-wrapper/src/main/java/com/github/[secure]/wkhtmltopdf/wrapper/Pdf.java:100: warning: no @param for source
[WARNING] public void addPageFromFile(String source) {
[WARNING] ^
[WARNING] /home/travis/build/[secure]/java-wkhtmltopdf-wrapper/src/main/java/com/github/[secure]/wkhtmltopdf/wrapper/Pdf.java:119: warning: no @param for timeout
[WARNING] public void setTimeout(int timeout) {
[WARNING] ^
[WARNING] /home/travis/build/[secure]/java-wkhtmltopdf-wrapper/src/main/java/com/github/[secure]/wkhtmltopdf/wrapper/Pdf.java:152: warning: no description for @param
[WARNING] * @param tempDirectory
[WARNING] ^
[WARNING] /home/travis/build/[secure]/java-wkhtmltopdf-wrapper/src/main/java/com/github/[secure]/wkhtmltopdf/wrapper/Pdf.java:161: warning: no description for @return
[WARNING] * @return
[WARNING] ^
[WARNING] /home/travis/build/[secure]/java-wkhtmltopdf-wrapper/src/main/java/com/github/[secure]/wkhtmltopdf/wrapper/Pdf.java:162: warning: no description for @throws
[WARNING] * @throws IOException
[WARNING] ^
[WARNING] /home/travis/build/[secure]/java-wkhtmltopdf-wrapper/src/main/java/com/github/[secure]/wkhtmltopdf/wrapper/Pdf.java:163: warning: no description for @throws
[WARNING] * @throws InterruptedException
[WARNING] ^
[WARNING] /home/travis/build/[secure]/java-wkhtmltopdf-wrapper/src/main/java/com/github/[secure]/wkhtmltopdf/wrapper/Pdf.java:175: warning: no description for @return
[WARNING] * @return
[WARNING] ^
[WARNING] /home/travis/build/[secure]/java-wkhtmltopdf-wrapper/src/main/java/com/github/[secure]/wkhtmltopdf/wrapper/Pdf.java:176: warning: no description for @throws
[WARNING] * @throws IOException
[WARNING] ^
[WARNING] /home/travis/build/[secure]/java-wkhtmltopdf-wrapper/src/main/java/com/github/[secure]/wkhtmltopdf/wrapper/Pdf.java:177: warning: no description for @throws
[WARNING] * @throws InterruptedException
[WARNING] ^
[WARNING] /home/travis/build/[secure]/java-wkhtmltopdf-wrapper/src/main/java/com/github/[secure]/wkhtmltopdf/wrapper/Pdf.java:283: warning: no description for @throws
[WARNING] * @throws IOException
[WARNING] ^

And maven warnings:

[WARNING] 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-surefire-plugin is missing. @ line 86, column 21
[WARNING] 
[WARNING] It is highly recommended to fix these problems because they threaten the stability of your build.
[WARNING] 
[WARNING] For this reason, future Maven versions might no longer support building such malformed projects.

[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!

Runtime Exception occurred while running the program to convert html to pdf document in Mac OS using wkhtml

Mac OS X
java.lang.RuntimeException
at com.github.jhonnymertz.wkhtmltopdf.wrapper.configurations.WrapperConfig.findExecutable(WrapperConfig.java:46)
at com.github.jhonnymertz.wkhtmltopdf.wrapper.configurations.WrapperConfig.(WrapperConfig.java:14)
at com.github.jhonnymertz.wkhtmltopdf.wrapper.Pdf.(Pdf.java:36)
at com.tgt.html_to_pdf_converter.HtmlToPdfConverter_Usingwkhtlwrapper.main(HtmlToPdfConverter_Usingwkhtlwrapper.java:13)
Mac OS X
Exception in thread "main" java.io.IOException: Cannot run program "wkhtmltopdf": error=2, No such file or directory
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
at java.lang.Runtime.exec(Runtime.java:620)
at java.lang.Runtime.exec(Runtime.java:485)
at com.github.jhonnymertz.wkhtmltopdf.wrapper.Pdf.getPDF(Pdf.java:95)
at com.tgt.html_to_pdf_converter.HtmlToPdfConverter_Usingwkhtlwrapper.main(HtmlToPdfConverter_Usingwkhtlwrapper.java:29)
Caused by: java.io.IOException: error=2, No such file or directory
at java.lang.UNIXProcess.forkAndExec(Native Method)
at java.lang.UNIXProcess.(UNIXProcess.java:247)
at java.lang.ProcessImpl.start(ProcessImpl.java:134)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
... 4 more

unable to generate pdf in case of unknown content error

when I use wkhtml outside java it created the pdf despite of the unknown content error but now when i came to know of this API, i implemented it in my project but in case of unknown content error it is not even generating the pdf file.

Allow Integration tests to run locally

Problem: Integration tests can only be executed with wkhtmltopdf in place, which is not always possible (for example CI/CD with travis).

Solution: embed wkhtmltopdf into the repo for testing purposes only

Chart js conversion not working

Not able create chart

public class PDFCreation1 {
public static void main(String[] args) throws IOException, InterruptedException {
Pdf pdf = new Pdf(new WrapperConfig("wkhtmltopdf"));
pdf.cleanAllTempFiles();

    pdf.addParam(new Param("--enable-javascript"));
   // pdf.addTocParam(new Param("--xsl-style-sheet", "my_toc.xsl"));

    // pdf.addParam();
    pdf.addPageFromFile("file:///C:/Users/sathishkumar_n/Desktop/pipechart.html");
    pdf.saveAs("C:\\Nsk\\PDF\\output1.pdf");
}

}

pipeChart.zip
output1.pdf

Environment (please complete the following information):

  • java-wkhtmltopdf-wrapper version:1.1.12
  • wkhtmltopdf version: 0.12.6

Release New version

Could we get a new release of this library? The dependency version bumps that are present in the master branch would be really nice to have.

Thanks so much for this great project!

HostNotFoundError - after updating to 1.1.4-RELEASE, reverting to 1.1.0-RELEASE fixes the problem

Hi, please see attached error output.

ERROR - Pdf                        - Error while generating pdf: Loading pages (1/6)
Warning: Failed loading page http: (ignored)                      
Warning: Failed loading page http://da (ignored)
Warning: Failed loading page http://xn--moravsk-12a (ignored)
Warning: Failed loading page http://60kva-header.html (ignored)
Warning: Failed loading page http://xn--moravsk-12a (ignored)
Warning: Failed loading page http: (ignored)
Warning: Failed loading page http://da (ignored)
Warning: Failed loading page http://60kva-footer.html (ignored)   
Counting pages (2/6)                                              
Resolving links (4/6)                                                       
Loading headers and footers (5/6)                                           
Warning: Failed loading page file:///data/tmp/Nabidka_190029_2019-01-17_2019-01-17_LIKO-S,a.s,?page=1&section=&sitepage=1&title=&subsection=&frompage=1&subsubsection=&isodate=2019-01-15&topage=10&doctitle=Rental.cz nabídka č. 190029 | start: 17.01.2019 08:00:00 | konec: 17.01.2019 16:00:00&sitepages=1&webpage=Moravský&time=22:00&date=15.01.19 (ignored)
Warning: Failed loading page file:///data/tmp/Nabidka_190029_2019-01-17_2019-01-17_LIKO-S,a.s,?page=2&section=&sitepage=1&title=&subsection=&frompage=1&subsubsection=&isodate=2019-01-15&topage=10&doctitle=Rental.cz nabídka č. 190029 | start: 17.01.2019 08:00:00 | konec: 17.01.2019 16:00:00&sitepages=1&webpage=Kočov,&time=22:00&date=15.01.19 (ignored)
Warning: Failed loading page file:///data/tmp/Nabidka_190029_2019-01-17_2019-01-17_LIKO-S,a.s,?page=3&section=&sitepage=1&title=&subsection=&frompage=1&subsubsection=&isodate=2019-01-15&topage=10&doctitle=Rental.cz nabídka č. 190029 | start: 17.01.2019 08:00:00 | konec: 17.01.2019 16:00:00&sitepages=1&webpage=DA&time=22:00&date=15.01.19 (ignored)
Warning: Failed loading page file:///data/tmp/Nabidka_190029_2019-01-17_2019-01-17_LIKO-S,a.s,?page=4&section=&sitepage=1&title=&subsection=&frompage=1&subsubsection=&isodate=2019-01-15&topage=10&doctitle=Rental.cz nabídka č. 190029 | start: 17.01.2019 08:00:00 | konec: 17.01.2019 16:00:00&sitepages=1&webpage=60kVA-header.html&time=22:00&date=15.01.19 (ignored)
Warning: Failed loading page file:///data/tmp/Nabidka_190029_2019-01-17_2019-01-17_LIKO-S,a.s,?page=4&section=&sitepage=1&title=&subsection=&frompage=1&subsubsection=&isodate=2019-01-15&topage=10&doctitle=Rental.cz nabídka č. 190029 | start: 17.01.2019 08:00:00 | konec: 17.01.2019 16:00:00&sitepages=1&webpage=60kVA-header.html&time=22:00&date=15.01.19 (ignored)
Warning: Failed loading page file:///data/tmp/Nabidka_190029_2019-01-17_2019-01-17_LIKO-S,a.s,?page=5&section=&sitepage=1&title=&subsection=&frompage=1&subsubsection=&isodate=2019-01-15&topage=10&doctitle=Rental.cz nabídka č. 190029 | start: 17.01.2019 08:00:00 | konec: 17.01.2019 16:00:00&sitepages=1&webpage=Moravský&time=22:00&date=15.01.19 (ignored)
Warning: Failed loading page file:///data/tmp/Nabidka_190029_2019-01-17_2019-01-17_LIKO-S,a.s,?page=6&section=&sitepage=1&title=&subsection=&frompage=1&subsubsection=&isodate=2019-01-15&topage=10&doctitle=Rental.cz nabídka č. 190029 | start: 17.01.2019 08:00:00 | konec: 17.01.2019 16:00:00&sitepages=1&webpage=Kočov,&time=22:00&date=15.01.19 (ignored)
Warning: Failed loading page file:///data/tmp/Nabidka_190029_2019-01-17_2019-01-17_LIKO-S,a.s,?page=7&section=&sitepage=1&title=&subsection=&frompage=1&subsubsection=&isodate=2019-01-15&topage=10&doctitle=Rental.cz nabídka č. 190029 | start: 17.01.2019 08:00:00 | konec: 17.01.2019 16:00:00&sitepages=1&webpage=DA&time=22:00&date=15.01.19 (ignored)
Warning: Failed loading page file:///data/tmp/Nabidka_190029_2019-01-17_2019-01-17_LIKO-S,a.s,?page=8&section=&sitepage=1&title=&subsection=&frompage=1&subsubsection=&isodate=2019-01-15&topage=10&doctitle=Rental.cz nabídka č. 190029 | start: 17.01.2019 08:00:00 | konec: 17.01.2019 16:00:00&sitepages=1&webpage=60kVA-footer.html&time=22:00&date=15.01.19 (ignored)
Warning: Failed loading page file:///data/tmp/Nabidka_190029_2019-01-17_2019-01-17_LIKO-S,a.s,?page=9&section=Sídlo:&sitepage=1&title=Rental.cz nabídka č. 190029 | start: 17.01.2019 08:00:00 | konec: 17.01.2019 16:00:00&subsection=&frompage=1&subsubsection=&isodate=2019-01-15&topage=10&doctitle=Rental.cz nabídka č. 190029 | start: 17.01.2019 08:00:00 | konec: 17.01.2019 16:00:00&sitepages=2&webpage=/opt/jetty/temp/java-wkhtmltopdf-wrapper78398c60-38a9-46b0-8392-7bb10a77173b6921811445407951915.html&time=22:00&date=15.01.19 (ignored)
Warning: Failed loading page file:///data/tmp/Nabidka_190029_2019-01-17_2019-01-17_LIKO-S,a.s,?page=10&section=Sídlo:&sitepage=2&title=Rental.cz nabídka č. 190029 | start: 17.01.2019 08:00:00 | konec: 17.01.2019 16:00:00&subsection=&frompage=1&subsubsection=&isodate=2019-01-15&topage=10&doctitle=Rental.cz nabídka č. 190029 | start: 17.01.2019 08:00:00 | konec: 17.01.2019 16:00:00&sitepages=2&webpage=/opt/jetty/temp/java-wkhtmltopdf-wrapper78398c60-38a9-46b0-8392-7bb10a77173b6921811445407951915.html&time=22:00&date=15.01.19 (ignored)
Printing pages (6/6)
Done                                                                        
Exit with code 1 due to network error: HostNotFoundError

ERROR - DefaultExceptionMapper     - Unexpected error occurred
com.github.jhonnymertz.wkhtmltopdf.wrapper.PDFExportException: Process (/usr/local/bin/wkhtmltopdf -T 24 -B 12 -L 6 -R 6 --enable-javascript --enable-forms --load-error-handling ignore --header-spacing 3 --header-html file:///data/tmp/Nabidka_190029_2019-01-17_2019-01-17_LIKO-S,a.s, Moravský Kočov, DA 60kVA-header.html --footer-html file:///data/tmp/Nabidka_190029_2019-01-17_2019-01-17_LIKO-S,a.s, Moravský Kočov, DA 60kVA-footer.html /opt/jetty/temp/java-wkhtmltopdf-wrapper78398c60-38a9-46b0-8392-7bb10a77173b6921811445407951915.html -) exited with status code 1:
Loading pages (1/6)
[>                                                           ] 0%
[>                                                           ] 1%
[=>                                                          ] 2%
[=>                                                          ] 3%
[==>                                                         ] 4%
[===>                                                        ] 5%
[===>                                                        ] 6%
[====>                                                       ] 7%
[====>                                                       ] 8%
[======>                                                     ] 10%
Warning: Failed loading page http: (ignored)                      
Warning: Failed loading page http://da (ignored)
Warning: Failed loading page http://xn--moravsk-12a (ignored)
Warning: Failed loading page http://60kva-header.html (ignored)
Warning: Failed loading page http://xn--moravsk-12a (ignored)
Warning: Failed loading page http: (ignored)
Warning: Failed loading page http://da (ignored)
[======>                                                     ] 11%
Warning: Failed loading page http://60kva-footer.html (ignored)   
[=======>                                                    ] 12%
[=======>                                                    ] 12%
[=======>                                                    ] 13%
[=======>                                                    ] 13%
[========>                                                   ] 14%
[============>                                               ] 20%
Counting pages (2/6)                                              
[======>                                                     ] Object 1 of 9
[=============>                                              ] Object 2 of 9
[===================>                                        ] Object 3 of 9
[==========================>                                 ] Object 4 of 9
[=================================>                          ] Object 5 of 9
[=======================================>                    ] Object 6 of 9
[==============================================>             ] Object 7 of 9
[====================================================>       ] Object 8 of 9
[============================================================] Object 9 of 9
Resolving links (4/6)                                                       
[======>                                                     ] Object 1 of 9
[=============>                                              ] Object 2 of 9
[===================>                                        ] Object 3 of 9
[==========================>                                 ] Object 4 of 9
[=================================>                          ] Object 5 of 9
[=======================================>                    ] Object 6 of 9
[==============================================>             ] Object 7 of 9
[====================================================>       ] Object 8 of 9
[============================================================] Object 9 of 9
Loading headers and footers (5/6)                                           
[>                                                           ] 0%
[>                                                           ] 1%
[=>                                                          ] 2%
[=>                                                          ] 3%
[==>                                                         ] 4%
[===>                                                        ] 5%
[===>                                                        ] 6%
[====>                                                       ] 7%
[====>                                                       ] 8%
[=====>                                                      ] 9%
[======>                                                     ] 10%
Warning: Failed loading page file:///data/tmp/Nabidka_190029_2019-01-17_2019-01-17_LIKO-S,a.s,?page=1&section=&sitepage=1&title=&subsection=&frompage=1&subsubsection=&isodate=2019-01-15&topage=10&doctitle=Rental.cz nabídka č. 190029 | start: 17.01.2019 08:00:00 | konec: 17.01.2019 16:00:00&sitepages=1&webpage=Moravský&time=22:00&date=15.01.19 (ignored)
Warning: Failed loading page file:///data/tmp/Nabidka_190029_2019-01-17_2019-01-17_LIKO-S,a.s,?page=2&section=&sitepage=1&title=&subsection=&frompage=1&subsubsection=&isodate=2019-01-15&topage=10&doctitle=Rental.cz nabídka č. 190029 | start: 17.01.2019 08:00:00 | konec: 17.01.2019 16:00:00&sitepages=1&webpage=Kočov,&time=22:00&date=15.01.19 (ignored)
Warning: Failed loading page file:///data/tmp/Nabidka_190029_2019-01-17_2019-01-17_LIKO-S,a.s,?page=3&section=&sitepage=1&title=&subsection=&frompage=1&subsubsection=&isodate=2019-01-15&topage=10&doctitle=Rental.cz nabídka č. 190029 | start: 17.01.2019 08:00:00 | konec: 17.01.2019 16:00:00&sitepages=1&webpage=DA&time=22:00&date=15.01.19 (ignored)
Warning: Failed loading page file:///data/tmp/Nabidka_190029_2019-01-17_2019-01-17_LIKO-S,a.s,?page=4&section=&sitepage=1&title=&subsection=&frompage=1&subsubsection=&isodate=2019-01-15&topage=10&doctitle=Rental.cz nabídka č. 190029 | start: 17.01.2019 08:00:00 | konec: 17.01.2019 16:00:00&sitepages=1&webpage=60kVA-header.html&time=22:00&date=15.01.19 (ignored)
Warning: Failed loading page file:///data/tmp/Nabidka_190029_2019-01-17_2019-01-17_LIKO-S,a.s,?page=4&section=&sitepage=1&title=&subsection=&frompage=1&subsubsection=&isodate=2019-01-15&topage=10&doctitle=Rental.cz nabídka č. 190029 | start: 17.01.2019 08:00:00 | konec: 17.01.2019 16:00:00&sitepages=1&webpage=60kVA-header.html&time=22:00&date=15.01.19 (ignored)
Warning: Failed loading page file:///data/tmp/Nabidka_190029_2019-01-17_2019-01-17_LIKO-S,a.s,?page=5&section=&sitepage=1&title=&subsection=&frompage=1&subsubsection=&isodate=2019-01-15&topage=10&doctitle=Rental.cz nabídka č. 190029 | start: 17.01.2019 08:00:00 | konec: 17.01.2019 16:00:00&sitepages=1&webpage=Moravský&time=22:00&date=15.01.19 (ignored)
Warning: Failed loading page file:///data/tmp/Nabidka_190029_2019-01-17_2019-01-17_LIKO-S,a.s,?page=6&section=&sitepage=1&title=&subsection=&frompage=1&subsubsection=&isodate=2019-01-15&topage=10&doctitle=Rental.cz nabídka č. 190029 | start: 17.01.2019 08:00:00 | konec: 17.01.2019 16:00:00&sitepages=1&webpage=Kočov,&time=22:00&date=15.01.19 (ignored)
Warning: Failed loading page file:///data/tmp/Nabidka_190029_2019-01-17_2019-01-17_LIKO-S,a.s,?page=7&section=&sitepage=1&title=&subsection=&frompage=1&subsubsection=&isodate=2019-01-15&topage=10&doctitle=Rental.cz nabídka č. 190029 | start: 17.01.2019 08:00:00 | konec: 17.01.2019 16:00:00&sitepages=1&webpage=DA&time=22:00&date=15.01.19 (ignored)
Warning: Failed loading page file:///data/tmp/Nabidka_190029_2019-01-17_2019-01-17_LIKO-S,a.s,?page=8&section=&sitepage=1&title=&subsection=&frompage=1&subsubsection=&isodate=2019-01-15&topage=10&doctitle=Rental.cz nabídka č. 190029 | start: 17.01.2019 08:00:00 | konec: 17.01.2019 16:00:00&sitepages=1&webpage=60kVA-footer.html&time=22:00&date=15.01.19 (ignored)
Warning: Failed loading page file:///data/tmp/Nabidka_190029_2019-01-17_2019-01-17_LIKO-S,a.s,?page=9&section=Sídlo:&sitepage=1&title=Rental.cz nabídka č. 190029 | start: 17.01.2019 08:00:00 | konec: 17.01.2019 16:00:00&subsection=&frompage=1&subsubsection=&isodate=2019-01-15&topage=10&doctitle=Rental.cz nabídka č. 190029 | start: 17.01.2019 08:00:00 | konec: 17.01.2019 16:00:00&sitepages=2&webpage=/opt/jetty/temp/java-wkhtmltopdf-wrapper78398c60-38a9-46b0-8392-7bb10a77173b6921811445407951915.html&time=22:00&date=15.01.19 (ignored)
Warning: Failed loading page file:///data/tmp/Nabidka_190029_2019-01-17_2019-01-17_LIKO-S,a.s,?page=10&section=Sídlo:&sitepage=2&title=Rental.cz nabídka č. 190029 | start: 17.01.2019 08:00:00 | konec: 17.01.2019 16:00:00&subsection=&frompage=1&subsubsection=&isodate=2019-01-15&topage=10&doctitle=Rental.cz nabídka č. 190029 | start: 17.01.2019 08:00:00 | konec: 17.01.2019 16:00:00&sitepages=2&webpage=/opt/jetty/temp/java-wkhtmltopdf-wrapper78398c60-38a9-46b0-8392-7bb10a77173b6921811445407951915.html&time=22:00&date=15.01.19 (ignored)
Printing pages (6/6)
[>                                                           ] Preparing
[======>                                                     ] Page 1 of 10
[============>                                               ] Page 2 of 10
[==================>                                         ] Page 3 of 10
[========================>                                   ] Page 4 of 10
[==============================>                             ] Page 5 of 10
[====================================>                       ] Page 6 of 10
[==========================================>                 ] Page 7 of 10
[================================================>           ] Page 8 of 10
[======================================================>     ] Page 9 of 10
[============================================================] Page 10 of 10
Done                                                                        
Exit with code 1 due to network error: HostNotFoundError

	at com.github.jhonnymertz.wkhtmltopdf.wrapper.Pdf.getPDF(Pdf.java:139)
	at com.github.jhonnymertz.wkhtmltopdf.wrapper.Pdf.saveAs(Pdf.java:117
	...

with 1.1.0-RELEASE the command line is:

/usr/local/bin/wkhtmltopdf -T 24 -B 12 -L 6 -R 6 --enable-javascript --enable-forms --load-error-handling ignore --header-spacing 3 --header-html file:///data/tmp/PracovniVykazTechnika_190029_2019-01-17_2019-01-17_LIKO-S,a.s, Moravský Kočov, DA 60kVA-header.html --footer-html file:///data/tmp/PracovniVykazTechnika_190029_2019-01-17_2019-01-17_LIKO-S,a.s, Moravský Kočov, DA 60kVA-footer.html -

and PDF gets generated ok

I believe this is the culprit:

Warning: Failed loading page http: (ignored)                      
Warning: Failed loading page http://da (ignored)
Warning: Failed loading page http://xn--moravsk-12a (ignored)
Warning: Failed loading page http://60kva-header.html (ignored)
Warning: Failed loading page http://xn--moravsk-12a (ignored)
Warning: Failed loading page http: (ignored)
Warning: Failed loading page http://da (ignored)

because something regarding to handling of whitespaces has changed.

So far I did not have time to fully look into it, quickly scanning commits that came after 1.1.0-RELEASE didn't give me any hints, so in case this error rings the bell for you, please fix it.

Thank you very much.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.