danfickle / openhtmltopdf

An HTML to PDF library for the JVM. Based on Flying Saucer and Apache PDF-BOX 2. With SVG image support. Now also with accessible PDF support (WCAG, Section 508, PDF/UA)!

Home Page:https://danfickle.github.io/pdf-templates/index.html

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

images are missing

revoorunischal opened this issue · comments

Hi ,
I have integrated PdfRendererBuilder to generate pdf file from html file and its working perfectly in the text and other stuffs but images are getting missed out . And I am also getting a warning msg as follows

com.openhtmltopdf.exception WARNING:: Can't read image file; unexpected problem for URI 'https://res.cloudinary.com/dffr0nets/image/upload/2341574.png'

This is generated pdf file
A0005_170608144956GCo.pdf

And this is the html display for the same code

image

Can you please let me know why this is happening and whats the solution . The same works fine if i execute in junit .
This is the file generated from JUNIT .
ADM001_170608145000z3t.pdf

Please help me out .

Issue got fixed .
This was because my tomcat server was not having the temp/ directory so it was failing to cache the image and ImageIO.read function was giving an IOException . This got fixed once i created a folder for this .

Hi,

To display the images/company logo, you have to keep the logo image inside the web application folder and access the same using relative path. If you want to render the PDF files using java components, you have to keep the image inside the java containers and use the same while constructing the html files. Please drop the email to vetrivel.msc@gmail.com to get more details on this.

Thanks
Vetrivel

I am getting the issue in wildfly 10 server
the image url works fine but openhtml throws warning.
Any workaround?

Hi @kaziabidazad

Is there any chance the URL is https and secured with letsencrypt? If so, only relatively modern releases of Java will accept the let’s encrypt certificate. Please make sure that java.net.url::openConnection returns a valid image for the URL.

I am trying to convert my html to pdf and it has an image in it. I am getting the following error.
com.openhtmltopdf.exception WARNING:: IO problem for {URL}/test.png

That url is internet facing and is accessible from the browser.

i face same issue for following URL
https://res.cloudinary.com/dffr0nets/image/upload/2341574.png

below URL accessible from browser and not print
com.openhtmltopdf.exception WARNING:: IO problem for https://upload.wikimedia.org/wikipedia/commons/6/6a/Mona_Lisa.jpg

I face the same problem. Im generating a PDF from HTML with an image in it.
It works fine locally but when i deploy it and try to do it i get:
WARNING [com.openhtmltopdf.exception] (default task-7) IO problem for {URL}
Did anyone find a solution for this?

commented

Same issue here

commented

Same here

commented

Did somebody resolved this issue?

same here

Same here, After building as jar file the image not loading.

any further insights about this issue?

UPDATE:
I just realized we weren't outputting details of the exception associated with a log message. I have changed that and will do a release in the next couple of days (all going well). Hopefully, this will let us track down this mystery!

Earlier I wrote:
I couldn't reproduce. Is anyone able to detail the URL/environment they are using?

I tried this program, firstly on Windows, then on ubuntu:latest docker container with default-jre installed (Java 11).

package com.example;

import java.io.FileOutputStream;
import java.io.IOException;

import com.openhtmltopdf.pdfboxout.PdfRendererBuilder;

public class App 
{
    public static void main( String[] args ) throws IOException
    {
        //try (FileOutputStream fos = new FileOutputStream("C:\\Users\\me\\Desktop\\res.pdf")) {
        try (FileOutputStream fos = new FileOutputStream("/home/res.pdf")) {
            PdfRendererBuilder builder = new PdfRendererBuilder();

            builder.toStream(fos);
            builder.useFastMode();
            builder.withHtmlContent("<body>Hello world!<img src=\"https://upload.wikimedia.org/wikipedia/commons/6/6a/Mona_Lisa.jpg\"/></body>", null);
            builder.run();
        }
    }
}

POM file:

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.example</groupId>
  <artifactId>demo</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>demo</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
        <groupId>com.openhtmltopdf</groupId>
        <artifactId>openhtmltopdf-pdfbox</artifactId>
        <version>1.0.9</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <version>3.2.4</version>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>shade</goal>
            </goals>
            <configuration>
              <transformers>
                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                  <mainClass>com.example.App</mainClass>
                </transformer>
              </transformers>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>

    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
        <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
        <plugin>
          <artifactId>maven-site-plugin</artifactId>
          <version>3.7.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-project-info-reports-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

To build:

mvn clean package

To run:

java -jar demo-1.0-SNAPSHOT.jar

Could someone assist me with the following error

com.openhtmltopdf.exception WARNING:: Bad URL given: /images/1.png

In the final output I couldn't see the images are being displayed. Did several workarounds but couldn't find the exact issue
here.

@danfickle could you please help me with above problem ?

If anyone wants to debug this before the next release, it would be a great help. You need to add this code before using the builder. This code will output details of the underlying exception:

            XRLog.setLoggerImpl(new JDKXRLogger(false, Level.INFO, new ConsoleHandler(), new Formatter(){
                @Override
                public String format(LogRecord record) {
                    String base = record.getLevel() + ":: " + record.getMessage();

                    if (record.getThrown() != null) {
                        base += " => " + record.getThrown().getClass().getName() + ":: " + record.getThrown().getMessage();

                        if (record.getThrown().getCause() != null) {
                            base += " caused by: " + record.getThrown().getCause().getClass().getName() + ":: " + record.getThrown().getCause().getMessage();
                        }
                    }

                    return base + '\n';
                }
            }));

@malindux, I think you have a separate issue. You are getting that message because your url has no scheme such as http:// of file:, etc. Are you providing a base url to the builder with your html?

If you have something like:

builder.withHtmlContent(html, "https://openhtmltopdf.com/document.html");

then the relative url referenced in your document (/images/1.png) would resolve to https://openhtmltopdf.com/images/1.png (assuming you haven't overridden the default url resolver).

If the images are in your resources folder you could use something like:

builder.withHtmlContent(html, SomeClass.class.getResource("/document.html").toExternalForm());

Notes:

  • We're assuming a maven setup, if using another build tool resources may be located elsewhere.
  • src/main/resources/document.html must exist, but may be an empty file.
  • Image is located at: src/main/resources/images/1.png.

@danfickle Actually what I have is a resource folder with all the images in it and I'm using Free Marker Templates to produce PDFs. Using toExternalForm() actually solved my issues. Thank you for your support.

hey i'm getting the same problem in my server
I had to add file: to my code like this to get the images in my test
Parametro rutaImg = new Parametro("RUTA_IMG", rutaImgStrb.append("file:").append(templateLocation))

but the i have the images in a system folder like this.
C:\b1c-d3447443-78aa-4885-832e-f1a1dffd60aa\b1c\wrkdirr\ventasDigitales\plantillas\plantillaLibranza\images

Should I add file as a prefix in this route to make it work?
final route would be like this
file:C:\b1c-d3447443-78aa-4885-832e-f1a1dffd60aa\b1c\wrkdirr\ventasDigitales\plantillas\plantillaLibranza\images

The path should be provided as a file URI. That would mean something like file://C:/foo/bar.png.

But don't build this yourself by adding prefixes etc. Just use the File or Path API. For example:

String myImage = new File("C:/foo/bar.png").toURI().toString();
commented

@danfickle's advice worked :)

Added this:

builder.withHtmlContent(html,ClassPathResource("/document.html").url.toExternalForm())

After that, considering I have an image in resources/static/png/img1.png, I can reference it in the <img> tag with this path: static/png/img1.png

Note: it will NOT work if you try to reference it like this: file:static/png/img1.png
Another note: the document.html file is a simple HTML file that contains a <p> saying it should not be deleted. It's placed directly in the resources folder.

Thanks!

Note: it will NOT work if you try to reference it like this: file:static/png/img1.png

Yes indeed. You specify a file: URI to point to an image that is not in your classpath, but is rather loaded from a filesystem location. In my case I have both classpath images (for predefined things like icons) plus filesystem images (user-provided images). If loading from the classpath then what you suggest is the correct approach.