java - iText – HTML 到 PDF - 图像不显示在 PDF 中

标签 java itextsharp itext relative-path html-to-pdf

我有一个包含文本、图像的 html 页面,我正在将 HTML 内容解析为 iText 以生成 PDF。在生成的 PDF 中,不显示包含的图像,只显示文本。

如果我传递像 D:/Deiva/CRs/HTMLPage/article-101-horz.jpg 这样的绝对路径,那么图像就会被打印出来。但是如果我尝试像

这样从服务器打印图像

http://localhost:8085/content/dam/article-101-h1.jpg 或 http://www.google.co.in/intl/en_ALL/images/logos/images_logo_lg.gif

那么它不会打印在 PDF 中。

注意:我正在使用 itextpdf-5.2.1.jar 生成 PDF。

我的 HTML 代码 (Article.html):

<html>
   <head>
   </head>
   <body>   
     <p>Generate PDF with image using iText.</p>
     <img src="http://localhost:8085/content/dam/article-10-h1.jpg"></img>
     <img src="http://www.google.co.in/intl/en_ALL/images/logos/imgs_logo_lg.gif"></img>
     <img class="right horz" src="D:/Deiva/CRs/HTMLPage/article-101-horz.jpg"></img>
   </body>
</html>

我正在使用以下 java 代码生成 PDF:

private void createPDF (){

  String path = "D:/Deiva/Test.pdf";
  PdfWriter pdfWriter = null;

  //create a new document
  Document document = new Document();

  try {

   //get Instance of the PDFWriter
   pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(path));

   //document header attributes
   document.addAuthor("betterThanZero");
   document.addCreationDate();
   document.addProducer();
   document.addCreator("MySampleCode.com");
   document.addTitle("Demo for iText XMLWorker");
   document.setPageSize(PageSize.LETTER);

   //open document
   document.open();
   InputStream is = new             FileInputStream("D:/Deiva/CRs/Oncology/Phase5/CR1/HTMLPage/Article.html");

   // create new input stream reader
   InputStreamReader isr = new InputStreamReader(is);

   //get the XMLWorkerHelper Instance
   XMLWorkerHelper worker = XMLWorkerHelper.getInstance();
   //convert to PDF
   worker.parseXHtml(pdfWriter, document, isr);

   //close the document
   document.close();
   //close the writer
   pdfWriter.close();

  } catch (Exception e) {
      e.printStackTrace();
  }

 }

请提出一个以 PDF 格式显示图像的解决方案。

提前致谢。

天神

最佳答案

我认为您可以使用用于查看图像的 Servlet 轻松完成此操作。如何为此编写 servlet here

这里有一个调度程序示例。只需根据需要编辑需要的地方

@Controller
public class ImageController extends DispatcherServlet {



    private static final int DEFAULT_BUFFER_SIZE = 10240; // 10KB.

    // Properties ---------------------------------------------------------------------------------

    private String imagePath;

   @RequestMapping(value="images/{imageId:.+}", method = RequestMethod.GET)
   public @ResponseBody void getImage(@PathVariable String imageId,HttpServletRequest request, HttpServletResponse response){
        String requestedImage = request.getPathInfo();
         this.imagePath ="image path in server here";

         if (requestedImage == null) {
             // Do your thing if the image is not supplied to the request URI.
             // Throw an exception, or send 404, or show default/warning image, or just ignore it.
             try {
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
             }catch(IOException ioException){
                logger.error("error image path incorrect:{}", ioException);

            } // 404.
             return;
         }

         File image=null;
        try {
            image = new File(imagePath, URLDecoder.decode(imageId, "UTF-8"));
        } catch (UnsupportedEncodingException unsupportedEncodingException) {
            logger.error("error image can not decode:{}", unsupportedEncodingException);

        }

         // Check if file actually exists in filesystem.
         if (!image.exists()) {
             // Do your thing if the file appears to be non-existing.
             // Throw an exception, or send 404, or show default/warning image, or just ignore it.
             try {
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
             }catch(IOException ioException){
                logger.error("error image does not exists:{}", ioException);

            } // 404.
             return;
         }

         // Get content type by filename.
         String contentType = "jpeg";
         contentType="image/"+contentType;

         // Init servlet response.
         response.reset();
         response.setBufferSize(DEFAULT_BUFFER_SIZE);
         response.setContentType(contentType);
         response.setHeader("Content-Length", String.valueOf(image.length()));
         response.setHeader("Content-Disposition", "inline; filename=\"" + image.getName() + "\"");

         // Prepare streams.
         BufferedInputStream input = null;
         BufferedOutputStream output = null;

         try {
             // Open streams.
             try {
                input = new BufferedInputStream(new FileInputStream(image), DEFAULT_BUFFER_SIZE);
            } catch (FileNotFoundException e) {

                logger.error("error creating file input stream to the image file :{}", e);


            }
             try {

                 output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);

            } catch (IOException e) {


                logger.error("error creating output stream to the http response :{}", e);

            }

             // Write file contents to response.
             byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
             int length;
             try {
                while ((length = input.read(buffer)) > 0) {
                     output.write(buffer, 0, length);
                 }
            } catch (IOException e) {

                logger.error("error writing the image file to outputstream :{}", e);

            }
         } finally {
             // Gently close streams.
             close(output);
             close(input);
         }
     }

     // Helpers (can be refactored to public utility class) ----------------------------------------




private  void close(Closeable resource) {
    if (resource != null) {
        try {
            resource.close();
        } catch (IOException e) {
            // Do your thing with the exception. Print it, log it or mail it.
            logger.error("error closing resources:{}", e);
        }
    }
}




}

关于java - iText – HTML 到 PDF - 图像不显示在 PDF 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15273933/

相关文章:

java - 当服务器仅发送其证书并且颁发者被授权信息访问引用时使用 TLS

java - 强制返回 JSON 的 Java Jersey RESTful Web 服务出现 HTTP 404 错误

c# - 在 C# 中使用 iTextSharp 阅读 pdf 内容

itextsharp - Y 期的 X 页

java - 在 iText7 的自定义签名外观签名中使用字体会破坏 PDF/A 一致性?

java - 将注释(XFDF 格式)合并到 PDF 中

c# - 如何在 iTextSharp 中旋转文本?

java - 确定贝塞尔曲线是否与圆重叠的最佳方法是什么?

java - 你指定的目标需要一个项目来执行但是这个目录下没有POM

pdf - iText - 如何将页面添加到使用 PdfCopy 创建的文档中