batik下载地址
https://xmlgraphics.apache.org/batik/download.html
下载完成后将相应jar包导入项目
@Test
public void testPDF() throws Exception {
// File f = new File("src/ceshi.svg");
File f = new File("src/0008.svg");
convertSvgFile2Pdf(f);
}
//svg文件转pdf
public static void convertSvgFile2Pdf(File file) throws IOException {
InputStream inputStream = new FileInputStream(file);
OutputStream outputStream = new FileOutputStream(new File("D:\\sun.pdf"));
outputStream = new BufferedOutputStream(outputStream);
try {
TranscoderOutput transcoderOutput = new TranscoderOutput(outputStream);
TranscoderInput transcoderInput = new TranscoderInput(inputStream);
// Transcoder transcoder = new PNGTranscoder();
// 转png
Transcoder transcoder = new PDFTranscoder();
transcoder.transcode(transcoderInput, transcoderOutput);
} catch (Exception e) {
e.printStackTrace();
} finally {
inputStream.close();
outputStream.close();
}
}
//字符串转pdf,svg文件的字符串形式
public static void convertSvgString2Pdf(String pageStr) throws IOException {
ByteArrayInputStream inputStream = new ByteArrayInputStream(pageStr.getBytes());
OutputStream outputStream = new FileOutputStream(new File("D:\\sun.pdf"));
outputStream = new BufferedOutputStream(outputStream);
try {
TranscoderOutput transcoderOutput = new TranscoderOutput(outputStream);
TranscoderInput transcoderInput = new TranscoderInput(inputStream);
// Transcoder transcoder = new PNGTranscoder();
// 转png
Transcoder transcoder = new PDFTranscoder();
transcoder.transcode(transcoderInput, transcoderOutput);
} catch (Exception e) {
e.printStackTrace();
} finally {
inputStream.close();
outputStream.close();
}
}
多张图片转PDF
/**
* @param outPdfFilepath 生成pdf文件路径
* @param imageFiles 需要转换的图片File类list,按list的顺序合成图片
*/
public static void imagesToPdf(String outPdfFilepath, List<File> imageFiles) throws Exception {
File file = new File(outPdfFilepath);
// 第一步:创建一个document对象。
Document document = new Document();
document.setMargins(0, 0, 0, 0);
// 第二步:创建一个PdfWriter实例,
PdfWriter.getInstance(document, new FileOutputStream(file));
// 第三步:打开文档。
document.open();
// 第四步:在文档中增加图片。
for (File imgFile : imageFiles) {
if (imgFile.getName().toLowerCase().endsWith(".bmp")
|| imgFile.getName().toLowerCase().endsWith(".jpg")
|| imgFile.getName().toLowerCase().endsWith(".jpeg")
|| imgFile.getName().toLowerCase().endsWith(".gif")
|| imgFile.getName().toLowerCase().endsWith(".png")) {
String temp = imgFile.getAbsolutePath();
Image img = Image.getInstance(temp);
img.setAlignment(Image.ALIGN_CENTER);
// img.scaleAbsolute(597, 844);// 直接设定显示尺寸
// 根据图片大小设置页面,一定要先设置页面,再newPage(),否则无效
document.setPageSize(new Rectangle(img.getWidth(), img.getHeight()));
// document.setPageSize(new Rectangle(597, 844));
document.newPage();
document.add(img);
}
}
// 第五步:关闭文档。
document.close();
}