我有一个html文件,其中包含二进制形式的图像 我想用java将其转换为pdf 有人可以帮我这个吗? Html文件包含Base64图像文件
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.itextpdf.text.Chunk;
public class Test{
public static void main(String args[]){
try {
Document document = new Document();
// step 2
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("Test.pdf"));
// step 3
document.open();
document.newPage();
document.add(new Chunk(""));
// step 4
XMLWorkerHelper.getInstance().parseXHtml(writer, document,new FileInputStream("/home/farheen/workspace/html.to.pdf/test.html"));
//step 5
document.close();
System.out.println( "PDF Created!" );
}catch (Exception e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:2)
您可以使用itext
使用here
中的此示例代码import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileOutputStream;
public class ImageExample {
public static void main(String[] args) {
Document document = new Document();
try {
PdfWriter.getInstance(document,
new FileOutputStream("Image.pdf"));
document.open();
Image image1 = Image.getInstance("watermark.png");
document.add(image1);
String imageUrl = "http://jenkov.com/images/" +
"20081123-20081123-3E1W7902-small-portrait.jpg";
Image image2 = Image.getInstance(new URL(imageUrl));
document.add(image2);
document.close();
} catch(Exception e){
e.printStackTrace();
}
}
}