java操作PDF文件方法之轉(zhuǎn)換、合成、切分
將PDF每一頁(yè)切割成圖片
PDFUtils.cutPNG("D:/tmp/1.pdf","D:/tmp/輸出圖片路徑/");
將PDF轉(zhuǎn)換成一張長(zhǎng)圖片
PDFUtils.transition_ONE_PNG("D:/tmp/1.pdf");
將多張圖片合并成一個(gè)PDF文件
PDFUtils.merge_PNG("D:/tmp/測(cè)試圖片/");
將多個(gè)PDF合并成一個(gè)PDF文件
PDFUtils.merge_PDF("D:/tmp/測(cè)試圖片/");
取出指定PDF的起始和結(jié)束頁(yè)碼作為新的pdf
PDFUtils.getPartPDF("D:/tmp/1.pdf",3,5);
引入依賴
<!-- apache PDF轉(zhuǎn)圖片-->
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.24</version>
</dependency>
<!-- itext 圖片合成PDF-->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.2</version>
</dependency>代碼(如下4個(gè)java類放在一起直接使用即可)
PDFUtils.java
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.*;
import org.apache.pdfbox.io.MemoryUsageSetting;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.apache.pdfbox.multipdf.Splitter;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* pdf工具類
*/
public class PDFUtils {
/**
* PDF分解圖片文件
*
* @param pdfPath pdf文件路徑
*/
public static void cutPNG(String pdfPath) throws IOException {
File pdf = new File(pdfPath);
cutPNG(pdfPath, pdf.getParent() + File.separator + pdf.getName() + "_pngs");
}
/**
* PDF分解圖片文件
*
* @param pdfPath pdf文件路徑
* @param outPath 輸出文件夾路徑
*/
public static void cutPNG(String pdfPath, String outPath) throws IOException {
File outDir = new File(outPath);
if (!outDir.exists()) outDir.mkdirs();
cutPNG(new File(pdfPath), outDir);
}
/**
* PDF分解圖片文件
*
* @param pdf pdf文件
* @param outDir 輸出文件夾
*/
public static void cutPNG(File pdf, File outDir) throws IOException {
LogUtils.info("PDF分解圖片工作開始");
List<BufferedImage> list = getImgList(pdf);
LogUtils.info(pdf.getName() + " 一共發(fā)現(xiàn)了 " + list.size() + " 頁(yè)");
FileUtils.cleanDir(outDir);
for (int i = 0; i < list.size(); i++) {
IMGUtils.saveImageToFile(list.get(i), outDir.getAbsolutePath() + File.separator + (i + 1) + ".png");
LogUtils.info("已保存圖片:" + (i + 1) + ".png");
}
LogUtils.info("PDF分解圖片工作結(jié)束,一共分解出" + list.size() + "個(gè)圖片文件,保存至:" + outDir.getAbsolutePath());
}
/**
* 將pdf文件轉(zhuǎn)換成一張圖片
*
* @param pdfPath pdf文件路徑
*/
public static void transition_ONE_PNG(String pdfPath) throws IOException {
transition_ONE_PNG(new File(pdfPath));
}
/**
* 將pdf文件轉(zhuǎn)換成一張圖片
*
* @param pdf pdf文件
*/
public static void transition_ONE_PNG(File pdf) throws IOException {
LogUtils.info("PDF轉(zhuǎn)換長(zhǎng)圖工作開始");
List<BufferedImage> list = getImgList(pdf);
LogUtils.info(pdf.getName() + " 一共發(fā)現(xiàn)了 " + list.size() + " 頁(yè)");
BufferedImage image = list.get(0);
for (int i = 1; i < list.size(); i++) {
image = IMGUtils.verticalJoinTwoImage(image, list.get(i));
}
byte[] data = IMGUtils.getBytes(image);
String imgPath = pdf.getParent() + File.separator + pdf.getName().replaceAll("\\.", "_") + ".png";
FileUtils.saveDataToFile(imgPath, data);
LogUtils.info("PDF轉(zhuǎn)換長(zhǎng)圖工作結(jié)束,合成尺寸:" + image.getWidth() + "x" + image.getHeight() + ",合成文件大小:" + data.length / 1024 + "KB,保存至:" + imgPath);
}
/**
* 將PDF文檔拆分成圖像列表
*
* @param pdf PDF文件
*/
private static List<BufferedImage> getImgList(File pdf) throws IOException {
PDDocument pdfDoc = PDDocument.load(pdf);
List<BufferedImage> imgList = new ArrayList<>();
PDFRenderer pdfRenderer = new PDFRenderer(pdfDoc);
int numPages = pdfDoc.getNumberOfPages();
for (int i = 0; i < numPages; i++) {
BufferedImage image = pdfRenderer.renderImageWithDPI(i, 300, ImageType.RGB);
imgList.add(image);
}
pdfDoc.close();
return imgList;
}
/**
* 圖片合成PDF
*
* @param pngsDirPath 圖片文件夾路徑
*/
public static void merge_PNG(String pngsDirPath) throws Exception {
File pngsDir = new File(pngsDirPath);
merge_PNG(pngsDir, pngsDir.getName() + ".pdf");
}
/**
* 圖片合成pdf
*
* @param pngsDir 圖片文件夾
* @param pdfName 合成pdf名稱
*/
private static void merge_PNG(File pngsDir, String pdfName) throws Exception {
File pdf = new File(pngsDir.getParent() + File.separator + pdfName);
if (!pdf.exists()) pdf.createNewFile();
File[] pngList = pngsDir.listFiles((dir, name) -> name.toLowerCase().endsWith(".png"));
LogUtils.info("在" + pngsDir.getAbsolutePath() + ",一共發(fā)現(xiàn)" + pngList.length + "個(gè)PNG文件");
Document document = new Document();
FileOutputStream fo = new FileOutputStream(pdf);
PdfWriter writer = PdfWriter.getInstance(document, fo);
document.open();
for (File f : pngList) {
document.newPage();
byte[] bytes = FileUtils.getFileBytes(f);
Image image = Image.getInstance(bytes);
float heigth = image.getHeight();
float width = image.getWidth();
int percent = getPercent2(heigth, width);
image.setAlignment(Image.MIDDLE);
image.scalePercent(percent + 3);// 表示是原來(lái)圖像的比例;
document.add(image);
System.out.println("正在合成" + f.getName());
}
document.close();
writer.close();
System.out.println("PDF文件生成地址:" + pdf.getAbsolutePath());
}
private static int getPercent2(float h, float w) {
int p = 0;
float p2 = 0.0f;
p2 = 530 / w * 100;
p = Math.round(p2);
return p;
}
/**
* 多PDF合成
*
* @param pngsDirPath pdf所在文件夾路徑
*/
public static void merge_PDF(String pngsDirPath) throws IOException {
File pngsDir = new File(pngsDirPath);
merge_PDF(pngsDir, pngsDir.getName() + "_合并.pdf");
}
/**
* 多PDF合成
*
* @param pngsDir pdf所在文件夾
* @param pdfName 合成pdf文件名
*/
private static void merge_PDF(File pngsDir, String pdfName) throws IOException {
File[] pdfList = pngsDir.listFiles((dir, name) -> name.toLowerCase().endsWith(".pdf"));
LogUtils.info("在" + pngsDir.getAbsolutePath() + ",一共發(fā)現(xiàn)" + pdfList.length + "個(gè)PDF文件");
PDFMergerUtility pdfMergerUtility = new PDFMergerUtility();
pdfMergerUtility.setDestinationFileName(pngsDir.getParent() + File.separator + pdfName);
for (File f : pdfList) {
pdfMergerUtility.addSource(f);
}
pdfMergerUtility.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
}
public static void getPartPDF(String pdfPath, int from, int end) throws Exception {
pdfPath = pdfPath.trim();
Document document = null;
PdfCopy copy = null;
PdfReader reader = new PdfReader(pdfPath);
int n = reader.getNumberOfPages();
if (end == 0) {
end = n;
}
document = new Document(reader.getPageSize(1));
copy = new PdfCopy(document, new FileOutputStream(pdfPath.substring(0, pdfPath.length() - 4) + "_" + from + "_" + end + ".pdf"));
document.open();
for (int j = from; j <= end; j++) {
document.newPage();
PdfImportedPage page = copy.getImportedPage(reader, j);
copy.addPage(page);
}
document.close();
}
}
IMGUtils.java
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class IMGUtils {
/**
* 將圖像轉(zhuǎn)為png文件的字節(jié)數(shù)據(jù)
* @param image 目標(biāo)圖像
* @return 返回?cái)?shù)據(jù)
*/
public static byte[] getBytes(BufferedImage image){
return getBytes(image,"png");
}
/**
* 將圖像轉(zhuǎn)換為指定媒體文件類型的字節(jié)數(shù)據(jù)
* @param image 目標(biāo)圖像
* @param fileType 文件類型(后綴名)
* @return 返回?cái)?shù)據(jù)
*/
public static byte[] getBytes(BufferedImage image,String fileType){
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
try {
ImageIO.write(image,fileType,outStream);
} catch (IOException e) {
e.printStackTrace();
}
return outStream.toByteArray();
}
/**
* 讀取圖像,通過(guò)文件
* @param filePath 文件路徑
* @return BufferedImage
*/
public static BufferedImage getImage(String filePath){
try {
return ImageIO.read(new FileInputStream(filePath));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 讀取圖像,通過(guò)字節(jié)數(shù)據(jù)
* @param data 字節(jié)數(shù)據(jù)
* @return BufferedImage
*/
public static BufferedImage getImage(byte[] data){
try {
return ImageIO.read(new ByteArrayInputStream(data));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 保存圖像到指定文件
* @param image 圖像
* @param filePath 文件路徑
*/
public static void saveImageToFile(BufferedImage image,String filePath) throws IOException {
FileUtils.saveDataToFile(filePath,getBytes(image));
}
/**
* 縱向拼接圖片
*/
public static BufferedImage verticalJoinTwoImage(BufferedImage image1, BufferedImage image2){
if(image1==null)return image2;
if(image2==null)return image1;
BufferedImage image=new BufferedImage(image1.getWidth(),image1.getHeight()+image2.getHeight(),image1.getType());
Graphics2D g2d = image.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2d.drawImage(image1, 0, 0, image1.getWidth(), image1.getHeight(), null);
g2d.drawImage(image2, 0, image1.getHeight(), image2.getWidth(), image2.getHeight(), null);
g2d.dispose();// 釋放圖形上下文使用的系統(tǒng)資源
return image;
}
/**
* 剪裁圖片
* @param image 對(duì)象
* @param x 頂點(diǎn)x
* @param y 頂點(diǎn)y
* @param width 寬度
* @param height 高度
* @return 剪裁后的對(duì)象
*/
public static BufferedImage cutImage(BufferedImage image,int x,int y,int width,int height){
if(image==null)return null;
return image.getSubimage(x,y,width,height);
}
}
FileUtils.java
import java.io.*;
public class FileUtils {
/**
* 將數(shù)據(jù)保存到指定文件路徑
*/
public static void saveDataToFile(String filePath,byte[] data) throws IOException {
File file = new File(filePath);
if(!file.exists())file.createNewFile() ;
FileOutputStream outStream = new FileOutputStream(file);
outStream.write(data);
outStream.flush();
outStream.close();
}
/**
* 讀取文件數(shù)據(jù)
*/
public static byte[] getFileBytes(File file) throws IOException {
if(!file.exists()||(file.exists()&&!file.isFile()))return null;
InputStream inStream=new FileInputStream(file);
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
inStream.close();
return outStream.toByteArray();
}
/**
* 讀取文本文件字
*/
public static String getFileText(String path){
try {
byte[] data= getFileBytes(new File(path));
return new String(data);
} catch (Exception e) {
return "";
}
}
/**
* 清空文件夾下所有文件
*/
public static void cleanDir(File dir){
if(dir!=null&&dir.isDirectory()){
for(File file:dir.listFiles()){
if(file.isFile())file.delete();
if(file.isDirectory())cleanDir(file);
}
}
}
}
LogUtils.java
public class LogUtils {
public static void info(String context){
System.out.println(context);
}
public static void warn(String context){
System.out.println(context);
}
public static void error(String context){
System.out.println(context);
}
}總結(jié)
到此這篇關(guān)于java操作PDF文件方法之轉(zhuǎn)換、合成、切分的文章就介紹到這了,更多相關(guān)java操作PDF轉(zhuǎn)換合成切分內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java設(shè)計(jì)模式中的工廠及抽象工廠模式解析
這篇文章主要介紹了Java設(shè)計(jì)模式中的工廠及抽象工廠模式解析,工廠模式作為創(chuàng)建型設(shè)計(jì)模式中常見(jiàn)的設(shè)計(jì)方法,一般情況下,工廠模式分為3種,簡(jiǎn)單工作、工廠方法、抽象工作,其實(shí)簡(jiǎn)單工廠只是工廠方法的一種特例,需要的朋友可以參考下2023-12-12
Java使用Condition控制線程通信的方法實(shí)例詳解
這篇文章主要介紹了Java使用Condition控制線程通信的方法,結(jié)合實(shí)例形式分析了使用Condition類同步檢測(cè)控制線程通信的相關(guān)操作技巧,需要的朋友可以參考下2019-09-09
使用Java實(shí)現(xiàn)對(duì)兩個(gè)秒級(jí)時(shí)間戳相加
在現(xiàn)代應(yīng)用程序開發(fā)中,時(shí)間戳的處理是一個(gè)常見(jiàn)需求,特別是當(dāng)我們需要對(duì)時(shí)間戳進(jìn)行運(yùn)算時(shí),比如時(shí)間戳的相加操作,本文我們將探討如何使用Java對(duì)兩個(gè)秒級(jí)時(shí)間戳進(jìn)行相加,并展示詳細(xì)的代碼示例和運(yùn)行結(jié)果,需要的朋友可以參考下2024-08-08
SpringBoot實(shí)現(xiàn)HTTP調(diào)用的七種方式總結(jié)
小編在工作中,遇到一些需要調(diào)用三方接口的任務(wù),就需要用到 HTTP 調(diào)用工具,這里,我總結(jié)了一下 實(shí)現(xiàn) HTTP 調(diào)用的方式,共有 7 種(后續(xù)會(huì)繼續(xù)新增),需要的朋友可以參考下2023-09-09
Java實(shí)現(xiàn)經(jīng)典游戲之大魚吃小魚
這篇文章主要為大家詳細(xì)介紹了如何利用Java語(yǔ)言實(shí)現(xiàn)經(jīng)典游戲之大魚吃小魚,文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)Java游戲開發(fā)有一定幫助,需要的可以參考一下2022-08-08
解決springboot jpa @Column columnDefinition等屬性失效問(wèn)題
這篇文章主要介紹了解決springboot jpa @Column columnDefinition等屬性失效問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-10-10

