<dependencies>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.8</version>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox-tools</artifactId>
<version>2.0.8</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.10</version>
</dependency>
</dependencies>
<VBox maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="600.0"
fx:controller="top.jialan75.pdfsize.controller.MainFrameController"
style="-fx-font-family: SansSerif"
prefWidth="825.0" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1">
<children>
<MenuBar fx:id="menuBar" prefHeight="25.0" prefWidth="650">
<!-- 设置action实际上是作用于它的MenuItem身上的 -->
<Menu text="功能">
<items>
<MenuItem onAction="#exportExcel" text="导出Excel"></MenuItem>
</items>
</Menu>
<!--<Menu onAction="#exportExcel" text="教程">-->
<!--<items>-->
<!--<MenuItem text="别看了没有"/>-->
<!--</items>-->
<!--</Menu>-->
</MenuBar>
<TableView fx:id="pdfTableView" prefHeight="600" prefWidth="820">
<columns>
<TableColumn prefWidth="50.0" fx:id="id" text="序号" style="-fx-alignment: center"/>
<TableColumn prefWidth="300" fx:id="name" text="文件名" style= "-fx-alignment: CENTER;" />
<TableColumn prefWidth="90" fx:id="image" text="图片" />
<TableColumn prefWidth="140.0" fx:id="size" text="尺寸" style="-fx-alignment: center"/>
<TableColumn prefWidth="50.0" fx:id="pageCount" text="页数" style="-fx-alignment: center"/>
<TableColumn prefWidth="70.0" fx:id="filesize" text="文件大小" style="-fx-alignment: center"/>
<TableColumn prefWidth="60.0" fx:id="openButton" text="打开PDF" style="-fx-alignment: center"/>
<TableColumn prefWidth="60.0" fx:id="delButton" text="移除" style="-fx-alignment: center"/>
</columns>
</TableView>
</children>
</VBox>
x
package top.jialan75.pdfsize.constant;
public class Constant {
public static int width = 825;
public static int height = 600;
public static String titile = "PDF获取尺寸";
}
package top.jialan75.pdfsize.controller;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.annotation.ExcelProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.DragEvent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.TransferMode;
import javafx.scene.text.Text;
import javafx.util.Callback;
import top.jialan75.pdfsize.entry.DemoData;
import top.jialan75.pdfsize.entry.Pdf;
import top.jialan75.pdfsize.utils.FxUtils;
import javax.swing.filechooser.FileSystemView;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
public class MainFrameController implements Initializable {
public static ObservableList<Pdf> data;
private TableView pdfTableView;
private TableColumn name,image,filesize, size, delButton, openButton, pageCount, id;
public void initialize(URL location, ResourceBundle resources) {
pdfTableView.setFixedCellSize(50.0);
//初始化 表头
initTableColumn();
//初始化 表格数据
data = FXCollections.observableArrayList();
//给窗口绑定表格
pdfTableView.setItems(data);
jiantingBiaoGeTuoZhuai(pdfTableView);
//给表格绑定双击事件
pdfTableView.setOnMouseClicked(new EventHandler<MouseEvent>() {
public void handle(MouseEvent event) {
if(event.getClickCount()==2){
String value = event.getTarget().toString();
System.out.println(value);
if(value.indexOf("pdf")!=-1){
String temp ="Text[text=\"";
value ="info/"+ value.substring(value.indexOf(temp)+temp.length(),value.lastIndexOf(".pdf"))+".png";
FxUtils.openFile(new File(value));
}
}
}
});
}
private static void jiantingBiaoGeTuoZhuai(TableView<Pdf> tableView) {
/**
* 给表格添加拖拽事件
*/
tableView.setOnDragOver(new EventHandler<DragEvent>() { //node添加拖入文件事件
public void handle(DragEvent event) {
Dragboard dragboard = event.getDragboard();
if (dragboard.hasFiles()) {
for (File file : dragboard.getFiles()) {
if (file.getAbsolutePath().endsWith(".pdf")) { //用来过滤拖入类型
event.acceptTransferModes(TransferMode.COPY);
break;
}
}
}
}
});
tableView.setOnDragDropped(new EventHandler<DragEvent>() { //拖入后松开鼠标触发的事件
public void handle(DragEvent event) {
Dragboard dragboard = event.getDragboard();
if (event.isAccepted()) {
for (File file : dragboard.getFiles()) {
if (file.getAbsolutePath().endsWith(".pdf")) { //用来过滤拖入类型
//添加数据
FxUtils.addToTableView(file, data);
}
}
}
}
});
}
private void initTableColumn() {
id.setCellValueFactory(new PropertyValueFactory<>("id"));
name.setCellValueFactory(new PropertyValueFactory<>("name"));
size.setCellValueFactory(new PropertyValueFactory<>("size"));
filesize.setCellValueFactory(new PropertyValueFactory<>("filesize"));
pageCount.setCellValueFactory(new PropertyValueFactory<>("pageCount"));
openButton.setCellValueFactory(new PropertyValueFactory<>("openButton"));
delButton.setCellValueFactory(new PropertyValueFactory<>("delButton"));
image.setCellValueFactory(new PropertyValueFactory<>("image"));
Callback<TableColumn, TableCell> value = new Callback<TableColumn, TableCell>() {
public TableCell call(TableColumn param) {
TableCell<Object, String> cell = new TableCell<>();
Text text = new Text();
cell.setGraphic(text);
cell.setPrefHeight(Control.USE_COMPUTED_SIZE);
text.wrappingWidthProperty().bind(name.widthProperty());
text.textProperty().bind(cell.itemProperty());
return cell;
}
};
name.setCellFactory(value);
}
public void exportExcel(ActionEvent actionEvent) {
List<DemoData> list= new ArrayList<>();
for(int i=0;i<data.size();i++){
Pdf pdf = data.get(i);
DemoData demoData = new DemoData();
demoData.setId(pdf.getId());
demoData.setName(pdf.getName());
demoData.setUrl(pdf.getImageUrl());
demoData.setSize(pdf.getSize());
demoData.setFilesize(pdf.getFilesize());
demoData.setPageCount(pdf.getPageCount());
demoData.setFile(pdf.getFile().toString());
list.add(demoData);
}
FileSystemView fsv = FileSystemView.getFileSystemView();
File com=fsv.getHomeDirectory();
String fileName = com.getPath()+"/"+System.currentTimeMillis()+".xls";
EasyExcel.write(fileName,DemoData.class).sheet("jialan75").doWrite(list);
}
}
package top.jialan75.pdfsize.entry;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.ContentRowHeight;
import java.net.URL;
50) (
100 / 8) (
public class DemoData {
value = "序号",index = 0) (
private int id;
value = "文件名",index = 1) (
private String name;
value = "图片",index = 2) (
private URL url;
value = "文件大小",index = 3) (
private String filesize;
value = "尺寸",index = 4) (
private String size;
value = "页数",index = 5) (
private String pageCount;
value = "完整路径",index = 6) (
private String file;
/**
* 忽略这个字段
* */
private String ignore;
public DemoData() {
}
public URL getUrl() {
return url;
}
public void setUrl(URL url) {
this.url = url;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public String getFilesize() {
return filesize;
}
public void setFilesize(String filesize) {
this.filesize = filesize;
}
public String getPageCount() {
return pageCount;
}
public void setPageCount(String pageCount) {
this.pageCount = pageCount;
}
public String getFile() {
return file;
}
public void setFile(String file) {
this.file = file;
}
public String getIgnore() {
return ignore;
}
public void setIgnore(String ignore) {
this.ignore = ignore;
}
}
package top.jialan75.pdfsize.entry;
import javafx.scene.control.Button;
import javafx.scene.image.ImageView;
import java.io.File;
import java.net.URL;
public class Pdf {
private int id;
private String name;
private ImageView image;
private String size;
private String filesize;
private String pageCount;
private Button delButton;
private Button openButton;
private File file;
private URL imageUrl;
public Pdf() {
}
public Pdf(int id, String name,ImageView image, String filesize, String size,String pageCount, Button delButton, Button openButton,File file,URL imageUrl) {
this.id = id;
this.name = name;
this.image = image;
this.size = size;
this.filesize = filesize;
this.delButton = delButton;
this.openButton = openButton;
this.pageCount = pageCount;
this.file = file;
this.imageUrl = imageUrl;
}
public String getFilesize() {
return filesize;
}
public void setFilesize(String filesize) {
this.filesize = filesize;
}
public URL getImageUrl() {
return imageUrl;
}
public void setImageUrl(URL imageUrl) {
this.imageUrl = imageUrl;
}
public ImageView getImage() {
return image;
}
public void setImage(ImageView image) {
this.image = image;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public String getPageCount() {
return pageCount;
}
public void setPageCount(String pageCount) {
this.pageCount = pageCount;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public Button getDelButton() {
return delButton;
}
public void setDelButton(Button delButton) {
this.delButton = delButton;
}
public Button getOpenButton() {
return openButton;
}
public void setOpenButton(Button openButton) {
this.openButton = openButton;
}
public boolean equals(Pdf that) {
if(this.name.equals(that.name)){
if(this.size.equals(that.size)){
if(this.filesize.equals(that.filesize)){
if(this.pageCount.equals(that.pageCount)){
if(this.file==that.file){
return true;
}
}
}
}
}
return false;
}
}
package top.jialan75.pdfsize.utils;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import top.jialan75.pdfsize.entry.Pdf;
import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;
public class FxUtils {
public static void addToTableView(final File file, final ObservableList<Pdf> data) {
Thread t3 = new Thread() {
public void run() {
Pdf pdf = createPdfByFile(file,data);
if(isFlag(pdf,data)){
System.out.println(pdf);
data.add(pdf);
for (int i = 0; i <data.size() ; i++) {
data.get(i).setId(i +1);
}
}
}
};
t3.start();
}
private static Pdf createPdfByFile(final File file, final ObservableList<Pdf> data) {
/**
* 根据文件名创建pdf对象
*/
final Button delButton = new Button("移除");
delButton.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
Pdf del=null;
for (Pdf po : data) {
if (po.getDelButton() == delButton) {
del=po;
break;
}
}
if (del!=null){
data.remove(del);
}
}
});
Button openButton = new Button("打开");
openButton.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
for (Pdf po : data) {
if (po.getFile() == file) {
openFile(po.getFile());
break;
}
}
}
});
Pdf pdf = new Pdf();
Map<String, String> map = PdfToImage.pdf2jpg(file.toString());
if(map!=null){
try {
ImageView imageView = new ImageView(new Image(new FileInputStream(map.get("fileName"))));
pdf.setImage(imageView);
pdf.setSize(map.get("size"));
pdf.setFilesize((int) (file.length() / 1024) + "kb");
pdf.setPageCount(map.get("pageCount"));
pdf.setFile(file);
pdf.setName(file.getName());
pdf.setId(data.size());
pdf.setImageUrl(new File(map.get("fileName")).toURI().toURL());
pdf.setDelButton(delButton);
pdf.setOpenButton(openButton);
double fitWidth = imageView.getImage().getWidth();
double fitHeight = imageView.getImage().getHeight();
double w = 45;
imageView.setFitHeight(w);
imageView.setFitWidth(w*fitWidth/fitHeight);
} catch (IOException e) {
e.printStackTrace();
}
}
return pdf;
}
public static void openFile(File file) {
Desktop desktop = Desktop.getDesktop();
if(file.exists()) {
try {
desktop.open(file);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static boolean isFlag(Pdf pdf,ObservableList<Pdf> data) {
boolean flag = true;
for (int i = 0; i < data.size(); i++) {
if(data.get(i).equals(pdf)){
flag = false;
break;
}
}
return flag;
}
}
package top.jialan75.pdfsize.utils;
import com.itextpdf.text.Document;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import java.io.File;
import java.io.FileOutputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PdfMergePdf {
public static void main(String[] args) {
String inPath = "\\\\tom\\d\\2022\\5 Finish\\白\\临时\\202204291348 22092750zeefset@W A34845 700g白 1200《1_80x180 2_80x180》.pdf";
String outPath = "\\\\tom\\d\\2022\\5 Finish\\白\\临时\\abc.pdf";
kaidanPdf(inPath,outPath,"small");
}
public static Map<String,String> kaidanPdf(String inPath, String outPath,String type) {
Map<String,String> map = new HashMap<>();
try {
if (!new File(outPath).getParentFile().exists()) {
new File(outPath).getParentFile().mkdirs();
}
PdfReader reader = new PdfReader(inPath);
Rectangle cropBox = reader.getCropBox(1);
float pt = 72 / 25.4f;
float pageWidth = cropBox.getWidth() / pt;
float pageHeight = cropBox.getHeight() / pt;
int pageCount = reader.getNumberOfPages();
map.put("pageCount",pageCount+"");
String sizeStr2 = "";
for(int i=1;i<=pageCount;i++){
Rectangle cropBoxStr = reader.getCropBox(i);
String pageWidthStr =formatDouble4( cropBoxStr.getWidth() / pt)+"";
String pageHeightStr = formatDouble4(cropBoxStr.getHeight() / pt)+"";
sizeStr2+=pageWidthStr+"x"+pageHeightStr+",";
}
sizeStr2 = sizeStr2.substring(0,sizeStr2.length()-1);
map.put("size",sizeStr2);
float maxWidth = pageWidth;
float maxHeight = pageHeight;
float space = 5;
if (type == "small") {
space = 1;
}
int col = 1;
int row = 1;
if (pageCount == 1) {
} else if (pageCount == 2) {
col = 2;
maxWidth = pageWidth * col + space * (col - 1);
} else if (pageCount == 3) {
col = 3;
maxWidth = pageWidth * col + space * (col - 1);
} else if (pageCount == 4) {
col = 2;
row = 2;
maxWidth = pageWidth * col + space * (col - 1);
maxHeight = pageHeight * row + space * (row - 1);
} else if (pageCount == 5 || pageCount == 6) {
col = 3;
row = 2;
maxWidth = pageWidth * col + space * (col - 1);
maxHeight = pageHeight * row + space * (row - 1);
} else if (pageCount == 7 || pageCount == 8) {
col = 4;
row = 2;
maxWidth = pageWidth * col + space * (col - 1);
maxHeight = pageHeight * row + space * (row - 1);
} else if (pageCount == 9) {
col = 3;
row = 3;
maxWidth = pageWidth * col + space * (col - 1);
maxHeight = pageHeight * row + space * (row - 1);
} else if (pageCount == 10 || pageCount == 11 || pageCount == 12) {
col = 4;
row = 3;
maxWidth = pageWidth * col + space * (col - 1);
maxHeight = pageHeight * row + space * (row - 1);
} else if (pageCount == 13 || pageCount == 14 || pageCount == 15) {
col = 5;
row = 3;
maxWidth = pageWidth * col + space * (col - 1);
maxHeight = pageHeight * row + space * (row - 1);
} else if (pageCount == 16) {
col = 4;
row = 4;
maxWidth = pageWidth * col + space * (col - 1);
maxHeight = pageHeight * row + space * (row - 1);
} else if (pageCount <= 20) {
col = 5;
row = 4;
maxWidth = pageWidth * col + space * (col - 1);
maxHeight = pageHeight * row + space * (row - 1);
} else if (pageCount <= 24) {
col = 6;
row = 4;
maxWidth = pageWidth * col + space * (col - 1);
maxHeight = pageHeight * row + space * (row - 1);
} else if (pageCount <= 30) {
col = 6;
row = 5;
maxWidth = pageWidth * col + space * (col - 1);
maxHeight = pageHeight * row + space * (row - 1);
} else if (pageCount <= 36) {
col = 6;
row = 6;
maxWidth = pageWidth * col + space * (col - 1);
maxHeight = pageHeight * row + space * (row - 1);
} else if (pageCount <= 48) {
col = 8;
row = 6;
maxWidth = pageWidth * col + space * (col - 1);
maxHeight = pageHeight * row + space * (row - 1);
} else if (pageCount <= 100) {
col = 10;
row = 10;
maxWidth = pageWidth * col + space * (col - 1);
maxHeight = pageHeight * row + space * (row - 1);
}
float pw = 420.0f;
float ph = 257.0f;
float baibian = 10;
if (type == "big") {
pw = maxWidth;
ph = maxHeight;
} else if (type == "mid") {
pw = maxWidth / 2;
ph = maxHeight / 2;
} else if (type == "small") {
baibian = 2;
pw = 30;
ph = maxHeight * pw / maxWidth;
}
float bw = pw / maxWidth;
float bl = bw;
float maxw = bw * maxWidth;
float maxh = bw * maxHeight;
baibian = 0;
Document document = new Document(new Rectangle((maxw + baibian) * pt, (maxh + baibian * 2) * pt));//新建一个文档并且设置页面大小
FileOutputStream outputStream = new FileOutputStream(outPath);//新建一个pdf文档;
PdfWriter writer = PdfWriter.getInstance(document, outputStream);//把新建的pdf 赋值给 document
writer.setPdfVersion(PdfWriter.VERSION_1_5);
document.open();//打开 document文档
PdfContentByte cb = writer.getDirectContent();
int k = 0;
for (int r = row - 1; r >= 0; r--) {
for (int c = 0; c < col; c++) {
k++;
if (k > pageCount) {
break;
}
PdfImportedPage importedPage = writer.getImportedPage(reader, k);
float width = importedPage.getWidth();
float height = importedPage.getHeight();
float w = reader.getBoxSize(k, "trim").getWidth();
float h = reader.getBoxSize(k, "trim").getHeight();
cb.addTemplate(importedPage, 1 * bl, 0, 0, 1 * bl, c * (width + space) * bl, r * (space + height) * bl);
}
}
outputStream.flush();//关闭文件
document.close();//关闭文件
outputStream.close();//关闭文件
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
public static String formatDouble4(double d) {
DecimalFormat df = new DecimalFormat("#.0");
String format = df.format(d);
System.out.println(format);
if (format.substring(format.length() - 2).equals(".0")) {
return format.substring(0, format.length() - 2);
}
return format;
}
}
package top.jialan75.pdfsize.utils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.pdfbox.tools.imageio.ImageIOUtil;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Map;
public class PdfToImage {
public static Map<String, String> pdf2jpg(String path) {
try {
String outPath = path.replaceAll(".pdf","ok.pdf");
new File(outPath).delete();
Map<String,String> mapStr = PdfMergePdf.kaidanPdf(path,outPath,"big");
System.out.println(mapStr);
long start = System.currentTimeMillis();
File file = new File(outPath);
PDDocument document = PDDocument.load(file);
String fileName = "info/" + file.getName().substring(0, file.getName().length() - 4) + ".png";
fileName = fileName.replaceAll("ok.png",".png");
if(!new File(fileName).exists()){
exportJpg(document, fileName);
}
mapStr.put("fileName", fileName);
document.close();
long end = System.currentTimeMillis();
System.out.println(fileName + ":" + (end - start) / 1000 + "秒");
new File(outPath).delete();
System.out.println(mapStr);
return mapStr;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static void exportJpg(PDDocument document, String fileName) throws IOException {
PDFRenderer pdfRenderer = new PDFRenderer(document);
BufferedImage bim = pdfRenderer.renderImageWithDPI(0, 120, ImageType.RGB);
ImageIOUtil.writeImage(bim, fileName, 120);
}
}
package top.jialan75.pdfsize;
//代码 :http://haotuo.net.cn/code/5/
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import top.jialan75.pdfsize.constant.Constant;
import java.io.File;
import java.net.URL;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
public void start(Stage primaryStage) throws Exception {
File file = new File("info/fxml/mainFrameFxml.fxml");
URL url = file.toURI().toURL();
Parent root = FXMLLoader.load(url);
primaryStage.setScene(new Scene(root, Constant.width, Constant.height));
primaryStage.setTitle(Constant.titile);
primaryStage.setResizable(false);
try {
Image asd = new Image("https://csdnimg.cn/release/blogv2/dist/pc/img/npsFeel1.png");
primaryStage.getIcons().add(asd);
}catch (Exception e){
}
primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
public void handle(WindowEvent event) {
System.out.println("程序退出了");
System.exit(0);
}
});
primaryStage.show();
}
}