Dei*_*iva 19 java relative-path itext itextsharp 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 or 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>
Run Code Online (Sandbox Code Playgroud)
我使用以下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();
}
}
Run Code Online (Sandbox Code Playgroud)
请建议一个以PDF格式显示图像的解决方案.
提前致谢.
德瓦玛丽娜
尝试将图像放入内存或字节流对象中,然后将该图像对象转换为 itextsharp 图像对象。
探索超载iTextSharp.text.Image
编辑:
虽然代码是用 C# 编写的,但它可能会对您有所帮助。
从本地驱动器获取图像:
Bitmap image1;
image1 = new Bitmap(@"C:\Documents and Settings\All Users\"
+ @"Documents\My Music\music.jpeg", true);
Run Code Online (Sandbox Code Playgroud)
注意::如果您的应用程序文件夹中有图像,那么我们有函数可以在 C# 中获取它们的本地文件路径。不知道Java。来自外部站点的图像可以下载为
System.Net.WebClient client = new WebClient();
client.DownloadFile(imageURL, localPathname); // look into java to get local path
Run Code Online (Sandbox Code Playgroud)
现在将此字节流转换为图像对象,如下所示
MemoryStream imgMemoryStream = new MemoryStream(imgByteArray);
Image myImage = Drawing.Image.FromStream(imgMemoryStream);
Run Code Online (Sandbox Code Playgroud)
现在,从中创建一个 iTextSharp 图像对象并将其添加到您的文档中,如下所示
iTextSharp.text.Image pic = iTextSharp.text.Image.GetInstance(myImage, System.Drawing.Imaging.ImageFormat.Jpeg);
document.Add(pic);
Run Code Online (Sandbox Code Playgroud)
希望这对您有帮助。
| 归档时间: |
|
| 查看次数: |
23457 次 |
| 最近记录: |