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分解圖片工作開(kāi)始");
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)圖工作開(kāi)始");
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)文章
Spring?Cloud?OpenFeign模版化客戶端搭建過(guò)程
OpenFeign是一個(gè)顯示聲明式的WebService客戶端。使用OpenFeign能讓編寫(xiě)Web Service客戶端更加簡(jiǎn)單,這篇文章主要介紹了Spring?Cloud?OpenFeign模版化客戶端,需要的朋友可以參考下2022-06-06
使用Swagger實(shí)現(xiàn)接口版本號(hào)管理方式
這篇文章主要介紹了使用Swagger實(shí)現(xiàn)接口版本號(hào)管理方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-10-10
Idea springboot如何實(shí)現(xiàn)批量啟動(dòng)微服務(wù)
這篇文章主要介紹了Idea springboot如何實(shí)現(xiàn)批量啟動(dòng)微服務(wù),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-05-05
使用SpringBoot請(qǐng)求方式和訪問(wèn)靜態(tài)頁(yè)面
SpringBoot支持多種請(qǐng)求方式,包括GET、RESTful、分頁(yè)列表等,常用框架如阿里fastjson、谷歌gson用于JavaBean序列化為Json,性能上Jackson最快,SpringBoot目錄結(jié)構(gòu)包括src/main/java、src/main/resources等2025-01-01
java 出現(xiàn)問(wèn)題javax.servlet.http.HttpServlet was not found解決方法
這篇文章主要介紹了java 出現(xiàn)問(wèn)題javax.servlet.http.HttpServlet was not found解決方法的相關(guān)資料,需要的朋友可以參考下2016-11-11
使用Postman自動(dòng)生成Cookie并轉(zhuǎn)換為Java代碼的實(shí)現(xiàn)
在接口測(cè)試中,有時(shí)候需要在請(qǐng)求中攜帶Cookie信息,為了方便測(cè)試,我們可以使用Postman來(lái)自動(dòng)生成Cookie,并將其轉(zhuǎn)換為Java代碼,以便在自動(dòng)化測(cè)試中使用,下面將介紹如何實(shí)現(xiàn)這一功能,需要的朋友可以參考下2024-11-11
window?下?win10?jdk8安裝與環(huán)境變量的配置過(guò)程
這篇文章主要介紹了window?下?win10?jdk8安裝與環(huán)境變量的配置,本文通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-08-08
Spring?Cloud?Stream實(shí)現(xiàn)數(shù)據(jù)流處理
Spring?Cloud?Stream的核心是Stream,準(zhǔn)確來(lái)講Spring?Cloud?Stream提供了一整套數(shù)據(jù)流走向(流向)的API,?它的最終目的是使我們不關(guān)心數(shù)據(jù)的流入和寫(xiě)出,而只關(guān)心對(duì)數(shù)據(jù)的業(yè)務(wù)處理,本文給大家介紹了Spring?Cloud?Stream實(shí)現(xiàn)數(shù)據(jù)流處理,需要的朋友可以參考下2024-11-11
Mybatis內(nèi)置參數(shù)之_parameter和_databaseId的使用
這篇文章主要介紹了Mybatis內(nèi)置參數(shù)之_parameter和_databaseId的使用方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-12-12
解決ThingsBoard編譯報(bào)錯(cuò)問(wèn)題:Failure?to?find?org.gradle:gradle-too
這篇文章主要介紹了ThingsBoard編譯報(bào)錯(cuò):Failure?to?find?org.gradle:gradle-tooling-api:jar:6.3,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-03-03

