分2步走
1. 把pdf文件转svg
利用java 来做 请下载包 spire.pdf-3.4.2.jar
main方法
package com.company;
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 java.io.File;
import java.io.FileInputStream;
import java.net.URL;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
File file = new File("info/fxml/mainFrame.fxml");
URL url = file.toURI().toURL();
Parent root = FXMLLoader.load(url);
primaryStage.setScene(new Scene(root, 400, 100));
primaryStage.setTitle("PDF转SVG");
primaryStage.setResizable(false);
Image image = new Image(new FileInputStream("info/img/logo.png"));
primaryStage.getIcons().add(image);
primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
@Override
public void handle(WindowEvent event) {
System.out.println("程序退出了");
System.exit(0);
}
});
primaryStage.show();
}
}
控制器
package com.company;
import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
public class MainFrame implements Initializable {
@FXML
private TextField t_data_pdf;
@FXML
private TextField t_data_svg;
private int k;
@FXML
private Button b_button_ht;
@Override
public void initialize(URL location, ResourceBundle resources) {
b_button_ht.setStyle("-fx-background-color: green");
}
public void work(ActionEvent actionEvent) {
pdf2svg(t_data_pdf.getText(),t_data_svg.getText());
}
private static void pdf2svg(String pdfPath, String svgPath) {
File[] files = new File(pdfPath).listFiles();
for(File file:files){
//转为单个svg
if(file.getName().toLowerCase().indexOf("pdf")==-1){
continue;
}
PdfDocument pdf = new PdfDocument(file.toString());
String parent =svgPath;
String parent2 =parent+"//temp";
new File(parent2).mkdirs();
String name = file.getName();
name = name.substring(0,name.lastIndexOf("."));
pdf.saveToFile(parent2+"/"+name+".svg", FileFormat.SVG);
List<String> listSvg = ReadAndWriteFile.readtFile(parent2 + "/" + name + ".svg", "utf-8");
pdf.close();
List<String> listResult = new ArrayList<>();
listResult.add("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
listResult.add("<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">");
for(String str:listSvg){
if(str.indexOf("<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\"")!=-1){
listResult.add(str);
}
}
listResult.add("<defs>");
listResult.add("</defs>");
listResult.add("<g transform=\"matrix(1.333333 0 0 1.333333 0 0)\">");
for(String str:listSvg){
if(str.indexOf("<path stroke=\"#")!=-1){
listResult.add(str);
}
}
listResult.add("</g>");
listResult.add("</svg>");
StringBuffer stringBuffer = new StringBuffer();
for(String str:listResult){
stringBuffer.append(str+"\n");
}
new File(parent2+"/"+name+".svg").delete();
ReadAndWriteFile.writeInFile(parent+"/"+name+".svg",stringBuffer.toString(),"utf-8");
String s = file.getParent() + "/over";
boolean exists = new File(s).exists();
if(!exists){
new File(s).mkdirs();
}
file.renameTo(new File(s+"/"+file.getName()));
}
}
public void working(ActionEvent actionEvent) {
Thread t2 = new Thread() {
public void run() {
while (true) {
if(k%2==0){
break;
}
long start = System.currentTimeMillis();
try {
pdf2svg(t_data_pdf.getText(),t_data_svg.getText());
sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
// System.out.println(new Date() + ">>>" + "\t处理文件:" + (end - start) + "ms");
}
}
};
if(new File(t_data_pdf.getText()).exists()&&new File(t_data_svg.getText()).exists()){
k++;
if(k%2==1){
if(new File(t_data_pdf.getText()).exists()&&new File(t_data_svg.getText()).exists()){
b_button_ht.setStyle("-fx-background-color: red");
t2.start();
}
}else{
b_button_ht.setStyle("-fx-background-color: green");
}
}
}
}
FXML
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<FlowPane xmlns="http://javafx.com/javafx"
xmlns:fx="http://javafx.com/fxml"
fx:controller="com.company.MainFrame"
style="-fx-font-family: SansSerif"
prefHeight="100.0" prefWidth="400.0">
<BorderPane fx:id="borderPane">
<center>
<GridPane style="-fx-hgap: 5;-fx-vgap: 5;-fx-padding: 5">
<Label prefWidth="80" GridPane.columnIndex="0" GridPane.rowIndex="0" text="PDF路径:"></Label>
<TextField fx:id="t_data_pdf" prefWidth="310" GridPane.columnIndex="1" GridPane.rowIndex="0"></TextField>
<Label prefWidth="80" GridPane.columnIndex="0" GridPane.rowIndex="1" text="SVG路径:"></Label>
<TextField fx:id="t_data_svg" prefWidth="310" GridPane.columnIndex="1" GridPane.rowIndex="1"></TextField>
</GridPane>
</center>
<bottom>
<HBox alignment="BASELINE_RIGHT" style="-fx-padding: 5">
<Button fx:id="b_button" onAction="#work" prefWidth="120" text="生成"></Button>
<Button fx:id="b_button_ht" onAction="#working" prefWidth="120" text="热文件夹监控" style="background-color:#fff;"></Button>
</HBox>
</bottom>
</BorderPane>
</FlowPane>
用到的工具类
package cn.net.haotuo.htutils.utils;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class ReadAndWriteFile {
/**
*
* @param path
* @param charsetName utf-8 gbk
* @return
*/
public static List<String> readtFile(String path,String charsetName) {
if(charsetName==null||charsetName.equals("")){
charsetName = "utf-8";
}
List<String> list = new ArrayList<>();
InputStreamReader read = null;// 考虑到编码格式
try {
read = new InputStreamReader(new FileInputStream(path), charsetName);
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = bufferedReader.readLine();
while ( lineTxt!=null){
list.add(lineTxt);
lineTxt = bufferedReader.readLine();
}
read.close();
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
/**
*
* @param path
* @param content utf-8 gbk
* @param charsetName
*/
public static void writeInFile(String path, String content,String charsetName) {
if(charsetName==null||charsetName.equals("")){
charsetName = "utf-8";
}
BufferedWriter writer = null;
StringBuilder outputString = new StringBuilder();
try {
outputString.append(content );
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path),charsetName));
writer.write(outputString.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
writer.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
}
}
2. 把svg的长度取出来,顺便把长度加在文件名上面
利用python来做
请安装此包
pip --default-timeout=100 install svgpathtools -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
import time
from threading import Thread
from svgpathtools import svg2paths
# pip --default-timeout=100 install svgpathtools -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
# pyinstaller -F
import os
# 获取目录下面文件夹
def get_files(path):
_list = []
for filepath,dirnames,filenames in os.walk(path):
for filename in filenames:
_list.append((filepath,filename))
return _list
# 获取svg的长度
def get_length(path):
paths, attributes = svg2paths(path)
sum = 0
for p in paths:
mypath = p
f = 1.333333333/(72/25.4)
sum += mypath.length()*f
return sum
# 把刀模长度增加在文件名上面
def add_len_to_name(a):
while True:
time.sleep(1)
if k%2 ==0 :
break
add_len_to_name2(p1)
# 把刀模长度增加在文件名上面
def add_len_to_name2(f):
for filepath,filename in get_files(f):
f2 = os.path.join(filepath, filename)
if 'over' in f2 or 'temp' in f2:
continue
len = int(get_length(f2) / 1.333333333)
if not os.path.exists(filepath + '/over'):
os.mkdir(filepath + '/over')
os.rename(f2, os.path.join(filepath + '/over/', str(len) + '-' + filename))
k = 0
p1 = ''
def long_io(cb):
def func(callback):
callback('ac')
t1 = Thread(target=func, args=(cb,))
t1.setDaemon(True)
t1.start()
def req_a():
global k
global p1
k = k+1
long_io(add_len_to_name)
if __name__ == '__main__':
import PySimpleGUI as sg
layout = [
[sg.Text("SVG路径"), sg.InputText(do_not_clear=True, key='n1')],
[sg.Button('运行'),sg.Button('热文件夹监控'),sg.Text(key='res')],
]
window = sg.Window('SVG计算长度', layout)
while True:
event, values = window.read()
if event == None:
break
if event == '运行':
add_len_to_name2(values['n1'])
if event == '热文件夹监控':
if k%2==0:
window['res'].update('热文件夹监控中.....')
p1 = values['n1']
req_a()
else:
k += 1
window['res'].update('')