21

テキスト、画像を含むhtmlページがあり、HTMLコンテンツをiTextに解析してPDFを生成しています。生成されたPDFでは、含まれている画像は表示されず、テキストのみが表示されます。

D:/Deiva/CRs/HTMLPage/article-101-horz.jpgのような絶対パスを渡すと、画像が印刷されます。しかし、サーバーから画像を印刷しようとすると、

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

その後、PDFに印刷されません。

注: PDFを生成するためにitextpdf-5.2.1.jarを使用しています。

私の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>

私はPDFを生成するために以下のJavaコードを使用しています:

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で表示するための解決策を提案してください。

前もって感謝します。

デイバ

4

5 に答える 5

4

画像を表示するサーブレットを使えば簡単にできると思います。このためのサーブレットの書き方はこちら

ここにサンプルのディスパッチャがあります。必要に応じて必要な場所を編集するだけです

@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);
        }
    }
}




}
于 2013-07-15T11:55:08.323 に答える
1

イメージをメモリまたはバイト ストリーム オブジェクトに取得してから、そのイメージ オブジェクトを itextsharp イメージ オブジェクトにキャストしてみてください。

のオーバーロードを調べるiTextSharp.text.Image

編集:

コードは C# ですが、参考になるかもしれません。

次のようにローカル ドライブからイメージを取得します。

Bitmap image1;
image1 = new Bitmap(@"C:\Documents and Settings\All Users\" 
            + @"Documents\My Music\music.jpeg", true);

注:アプリケーション フォルダーに画像がある場合は、C# でそれらのローカル ファイル パスを取得する関数があります。Javaについてはわかりません。外部サイトからの画像は次のようにダウンロードできます

System.Net.WebClient client = new WebClient();
client.DownloadFile(imageURL, localPathname);   // look into java to get local path

このバイト ストリームを次のようにイメージ オブジェクトに変換します。

MemoryStream imgMemoryStream = new MemoryStream(imgByteArray);
Image myImage = Drawing.Image.FromStream(imgMemoryStream);

そこから iTextSharp 画像オブジェクトを作成し、それを次のようにドキュメントに追加します。

iTextSharp.text.Image pic = iTextSharp.text.Image.GetInstance(myImage, System.Drawing.Imaging.ImageFormat.Jpeg);
document.Add(pic);

これがお役に立てば幸いです。

于 2013-03-09T15:49:45.617 に答える
1

私も同じ問題に直面しました..

しかし、それは画像の絶対パスで動作していました。リモートパスでは機能していないようです。ここでidが行ったことは、ファイルシステムの一時的な場所に画像を保存し、 pdf を生成し、最終的に一時的な場所から画像ファイルを削除することです。

<img src="/home/jboss/temp/imgs/img.png"/>
于 2014-12-12T07:52:03.717 に答える