0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Pdfboxでpdf変換 改訂

Posted at
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.mozilla.universalchardet.UniversalDetector;

public class Main {
    public static void main(String[] args) {
        try (PDDocument doc = new PDDocument()) {

            PDPage page = new PDPage(PDRectangle.A4);
            doc.addPage(page);
            setupText(doc, page);

            doc.save("C:\\Users\\hayaj\\OneDrive\\デスクトップ\\PDF変換\\output\\output.pdf");

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static void setupText(PDDocument doc, PDPage page) throws IOException {

        PDFont font = PDType0Font.load(doc,
                new FileInputStream("C:\\Users\\hayaj\\OneDrive\\デスクトップ\\PDF変換\\GenShinGothic-Bold.ttf"));

        try (PDPageContentStream cs = new PDPageContentStream(doc, page)) {

            cs.beginText();
            float startX = PDRectangle.A4.getLowerLeftX() + 50;
            float startY = PDRectangle.A4.getUpperRightY() - 50;
            float leading = calculateFontHeight(font, 12);
            float width = PDRectangle.A4.getWidth() - 100;
            Paragraph para = new Paragraph(width, font, 12);
            para.drawString(cs, getText(), startX, startY, leading, doc, page);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static String getText() throws IOException {
        String filePath = "C:\\Users\\hayaj\\OneDrive\\デスクトップ\\PDF変換\\input\\eucjp.txt";
        String charCode = getCharCode(filePath);
        try {
            String fileContent = readFileToString(filePath, charCode);
            System.out.println("ファイルの内容:\n" + fileContent);
            return fileContent;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String readFileToString(String filePath, String charCode) throws IOException {
        StringBuilder content = new StringBuilder();

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), charCode))) {
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line).append("\n");
            }
        }

        return content.toString();
    }

    private static String getCharCode(String filePath) throws IOException {
        byte[] buf = new byte[4096];
        try (FileInputStream fis = new FileInputStream(filePath)) {
            UniversalDetector detector = new UniversalDetector(null);
            int nread;
            while ((nread = fis.read(buf)) > 0 && !detector.isDone()) {
                detector.handleData(buf, 0, nread);
            }
            detector.dataEnd();
            String encoding = detector.getDetectedCharset();
            if (encoding != null) {
                System.out.println("Detected encoding = " + encoding);
            } else {
                System.out.println("No encoding detected.");
            }
            detector.reset();
            return encoding;
        }
    }

    private static float calculateFontHeight(PDFont font, int fontSize) throws IOException {
        return font.getFontDescriptor().getFontBoundingBox().getHeight() / 1000 * fontSize;
    }
}

class Paragraph {
    private PDFont font;
    private float width;
    private int fontSize;

    public Paragraph(float width, PDFont font, int fontSize) {
        this.width = width;
        this.font = font;
        this.fontSize = fontSize;
    }

    public void drawString(PDPageContentStream content, String text, float startX, float startY, float leading, PDDocument doc, PDPage page) {
        try {
            content.setFont(font, fontSize);
            float currentY = startY;
            List<String> lines = lines(text);
            for (String line : lines) {
                if (protrude(line)) {
                    content.showText(line);
                    content.newLineAtOffset(0, -leading);
                    currentY -= leading;
                    if (currentY <= PDRectangle.A4.getLowerLeftY() + 50) {
                        content.endText();
                        content.close();
                        page = new PDPage(PDRectangle.A4);
                        doc.addPage(page);
                        content = new PDPageContentStream(doc, page);
                        content.beginText();
                        content.setFont(font, fontSize);
                        currentY = PDRectangle.A4.getUpperRightY() - 50;
                    }
                } else {
                    content.showText(line);
                    content.newLineAtOffset(0, -leading);
                    currentY -= leading;
                }
            }
            content.endText();
            content.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    protected List<String> lines(String text) {
        List<String> lines = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < text.length(); i++) {
            sb.append(text.charAt(i));
            if (protrude(sb.toString()) || text.charAt(i) == '\n') {
                lines.add(sb.toString().replaceAll("\\p{C}", ""));
                sb.setLength(0);
            }
        }
        if (sb.length() > 0) {
            lines.add(sb.toString().replaceAll("\\p{C}", ""));
        }
        return lines;
    }

    private boolean protrude(String line) {
        try {
            return (font.getStringWidth(line.replaceAll("\\p{C}", "")) / 1000 * fontSize) > width;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?