JAVA实现PDF文件与图片的相互转换
发表时间:2023-04-11 16:34:24点击:2752
1、PDF转图片
先引入依赖
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.24</version>
</dependency>
demo代码如下:
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
private static void pdfToImage(){
try {
PDDocument document = PDDocument.load(new File("D:\\Test\\test.pdf"));
PDFRenderer renderer = new PDFRenderer(document);
BufferedImage image = renderer.renderImage(0);
ImageIO.write(image, "png", new File("D:\\Test\\output.png"));
document.close();
}catch (Exception e){
e.printStackTrace();
}
}
2、图片转PDF
对应需要的依赖包
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.4.2</version>
</dependency>
demo代码如下:
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;
private static void imageToPdf(){
try {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream("D:\\Test\\test2.pdf"));
document.open();
Image image = Image.getInstance("D:\\Test\\output.png");
document.add(image);
document.close();
}catch (Exception e){
e.printStackTrace();
}
}
怎么样?是不是觉得很简单呢
*原创文章,转载请注明出处