From c15fe6d34afc94c95a1c9f496649b405163337a2 Mon Sep 17 00:00:00 2001
From: 杜洪波 <1074825718@qq.com>
Date: 星期一, 18 八月 2025 15:51:14 +0800
Subject: [PATCH] java代码转PDF

---
 src/main/java/com/product/file/util/PDFOperateUtil.java |  149 +++++++++++++++++++++++++++++++++++++++++++++++--
 1 files changed, 143 insertions(+), 6 deletions(-)

diff --git a/src/main/java/com/product/file/util/PDFOperateUtil.java b/src/main/java/com/product/file/util/PDFOperateUtil.java
index 7487152..7f83868 100644
--- a/src/main/java/com/product/file/util/PDFOperateUtil.java
+++ b/src/main/java/com/product/file/util/PDFOperateUtil.java
@@ -4,12 +4,14 @@
 import java.io.BufferedReader;
 import java.io.File;
 import java.io.FileInputStream;
+import java.io.FileReader;
 import java.io.IOException;
 import java.io.InputStreamReader;
 import java.nio.charset.StandardCharsets;
 
 import javax.imageio.ImageIO;
 
+import org.apache.fontbox.ttf.TrueTypeCollection;
 import org.apache.pdfbox.pdmodel.PDDocument;
 import org.apache.pdfbox.pdmodel.PDPage;
 import org.apache.pdfbox.pdmodel.PDPageContentStream;
@@ -20,6 +22,132 @@
 
 public class PDFOperateUtil {
 
+	
+	public static void createPdfWithCode(String javaFilePath, String outputPath) throws IOException {
+        String javaCode = readJavaFileWithComments(javaFilePath);
+        
+        try (PDDocument document = new PDDocument()) {
+            PDPage page = new PDPage(PDRectangle.A4);
+            document.addPage(page);
+     
+            // 鍔犺浇瀛椾綋锛堝 SimSun锛�
+            File fontFile = getSystemFontFile();
+            if (!fontFile.exists()) {
+                throw new IOException("鏈壘鍒颁腑鏂囧瓧浣撴枃浠�");
+            }
+            TrueTypeCollection ttc = new TrueTypeCollection(fontFile);
+         // 閫氳繃瀛椾綋鍚嶇О鑾峰彇锛堝 "SimSun"锛�
+            PDType0Font font = PDType0Font.load(document, ttc.getFontByName("SimSun"), true);
+//            PDType0Font font = PDType0Font.load(document, fontFile);
+            float fontSize = 10;
+            float margin = 50;
+            float leading = 1.2f * fontSize; // 琛岃窛
+     
+            // 鍙敤瀹藉害 = 椤甸潰瀹藉害 - 宸﹀彸杈硅窛
+            PDRectangle mediaBox = page.getMediaBox();
+            float availableWidth = mediaBox.getWidth() - 2 * margin;
+     
+            // 鍒濆 Y 浣嶇疆锛堜粠椤堕儴寮�濮嬶級
+            float yPosition = mediaBox.getHeight() - margin;
+            float startX = margin;
+     
+            // 鍒嗗壊浠g爜涓鸿
+            String[] lines = javaCode.split("\n");
+     
+            PDPageContentStream contentStream = null;
+            try {
+                contentStream = new PDPageContentStream(document, page);
+                contentStream.setFont(font, fontSize);
+     
+                for (String line : lines) {
+                    // 濡傛灉褰撳墠琛岃秴鍑洪〉闈㈠簳閮紝鎹㈤〉
+                    if (yPosition < margin) {
+                        contentStream.close();
+                        page = new PDPage(PDRectangle.A4);
+                        document.addPage(page);
+                        yPosition = mediaBox.getHeight() - margin;
+                        contentStream = new PDPageContentStream(document, page);
+                        contentStream.setFont(font, fontSize);
+                    }
+     
+                    // 澶勭悊瓒呭琛岋細鎸夊瓧绗︽媶鍒嗗苟鎹㈣
+                    while (!line.isEmpty()) {
+                        // 璁$畻褰撳墠琛岃兘瀹圭撼鐨勬渶澶у瓧绗︽暟
+                        int maxChars = calculateMaxChars(font, fontSize, line, availableWidth);
+                        String subLine = line.substring(0, Math.min(maxChars, line.length()));
+                        line = line.substring(subLine.length());
+     
+                        // 鍐欏叆褰撳墠瀛愯
+                        writeTextLine(contentStream, subLine, startX, yPosition);
+                        yPosition -= leading;
+     
+                        // 濡傛灉鍓╀綑鍐呭浠嶈秴鍑洪〉闈㈠簳閮紝鎹㈤〉
+                        if (yPosition < margin && !line.isEmpty()) {
+                            contentStream.close();
+                            page = new PDPage(PDRectangle.A4);
+                            document.addPage(page);
+                            yPosition = mediaBox.getHeight() - margin;
+                            contentStream = new PDPageContentStream(document, page);
+                            contentStream.setFont(font, fontSize);
+                        }
+                    }
+                }
+            } finally {
+                if (contentStream != null) {
+                    contentStream.close();
+                }
+            }
+     
+            document.save(outputPath);
+        }
+    }
+ 
+    // 璁$畻涓�琛岃兘瀹圭撼鐨勬渶澶у瓧绗︽暟
+    private static int calculateMaxChars(PDType0Font font, float fontSize, String text, float availableWidth) throws IOException {
+        float width = 0;
+        int i = 0;
+        for (; i < text.length(); i++) {
+            width += font.getWidth(text.charAt(i)) / 1000 * fontSize;
+            if (width > availableWidth) {
+                break;
+            }
+        }
+        return i;
+    }
+ 
+    // 鍐欏叆鍗曡鏂囨湰锛堝乏瀵归綈锛�
+    private static void writeTextLine(PDPageContentStream contentStream, String text, float x, float y) throws IOException {
+        contentStream.beginText();
+        contentStream.newLineAtOffset(x, y);
+        contentStream.showText(text);
+        contentStream.endText();
+    }
+	
+	/**
+     * 璇诲彇 Java 鏂囦欢鍐呭锛堜繚鐣欐敞閲婂拰绌鸿锛�
+     */
+    private static String readJavaFileWithComments(String filePath) throws IOException {
+        StringBuilder codeBuilder = new StringBuilder();
+        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
+            String line;
+            while ((line = reader.readLine()) != null) {
+            	line = line.replace("\t", "    ");
+                // 淇濈暀鎵�鏈夎锛堝寘鎷敞閲婂拰绌鸿锛�
+                codeBuilder.append(line).append("\n");
+            }
+        }
+        return codeBuilder.toString();
+    }
+    
+    /**
+     * 璁$畻瀛椾綋楂樺害锛堝熀浜庡瓧浣撶殑 Ascent 鍜� Descent锛�
+     */
+    private static float calculateFontHeight(PDType0Font font, float fontSize) {
+        float ascent = font.getFontDescriptor().getAscent();
+        float descent = font.getFontDescriptor().getDescent();
+        return (ascent - descent) / 1000 * fontSize;
+    }
+ 
 	/**
 	 * 鏍规嵁鏂囨湰鏂囦欢鍒涘缓 PDF锛堜娇鐢� PDFBox锛�
 	 * 
@@ -29,7 +157,7 @@
 	 */
 	public static void createPdfFromTextFile(String textFilePath, String pdfFilePath) throws IOException {
 		String content = readTextFile(textFilePath);
-		 
+		content = content.replace("\t", "    ");
 		try (PDDocument document = new PDDocument()) {
             PDPage page = new PDPage(PDRectangle.A4);
             document.addPage(page);
@@ -39,12 +167,16 @@
             if (!fontFile.exists()) {
                 throw new IOException("鏈壘鍒版敮鎸佺殑涓枃瀛椾綋鏂囦欢锛圵indows/Linux锛�");
             }
+            TrueTypeCollection ttc = new TrueTypeCollection(fontFile);
+
+         // 閫氳繃瀛椾綋鍚嶇О鑾峰彇锛堝 "SimSun"锛�
+            PDType0Font font = PDType0Font.load(document, ttc.getFontByName("SimSun"), true);
  
             // 鍔犺浇瀛椾綋
-            PDType0Font font;
-            try (FileInputStream fontStream = new FileInputStream(fontFile)) {
-                font = PDType0Font.load(document, fontStream);
-            }
+//            PDType0Font font;
+//            try (FileInputStream fontStream = new FileInputStream(fontFile)) {
+//                font = PDType0Font.load(document, fontStream);
+//            }
  
             // 鍐欏叆 PDF 鍐呭
             try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
@@ -132,6 +264,10 @@
         if (os.contains("win")) {
             // Windows 瀛椾綋鐩綍锛堜紭鍏堟鏌ュ父瑙佷腑鏂囧瓧浣擄級
             possiblePaths = new String[]{
+//            	System.getenv("WINDIR") + "\\Fonts\\arial.ttf",  // 
+//            	System.getenv("WINDIR") + "\\Fonts\\simkai.ttf",  // 妤蜂綋
+//            	System.getenv("WINDIR") + "\\Fonts\\simfang.ttf",  // 瀹嬩綋
+            	System.getenv("WINDIR") + "\\Fonts\\simsun.ttc",  // 瀹嬩綋
                 System.getenv("WINDIR") + "\\Fonts\\simhei.ttf",  // 榛戜綋
                 System.getenv("WINDIR") + "\\Fonts\\msyh.ttc",   // 寰蒋闆呴粦
                 System.getenv("WINDIR") + "\\Fonts\\mingliu.ttc"  // 鏄庝綋锛堝鐢級
@@ -162,7 +298,8 @@
 	public static void main(String[] args) {
 		try {
 			// 1. 浠庢枃鏈枃浠跺垱寤� PDF
-			createPdfFromTextFile("E://鏂板缓1.txt", "E://鏂板缓1.pdf");
+//			createPdfFromTextFile("E://鏂板缓1.txt", "E://鏂板缓1.pdf");
+			createPdfWithCode("E:\\PROJECT\\Product\\鍚庣\\product\\product-server\\product-server-file\\src\\main\\java\\com\\product\\file\\util\\FileUtil.java", "E://鏂板缓1.pdf");
 
 			// 2. 璇诲彇 PDF 鍐呭
 			String content = readPdfContent("E://鏂板缓1.pdf");

--
Gitblit v1.9.2