使用Apache PDFBox显示PDF的所有页面

时间:2016-03-10 14:58:20

标签: java swing pdfbox

我是Apache PDFBox的新手,我使用org.apache.pdfbox.PDFReader打开PDF等, 但是现在我需要在JFrame PDF文档中显示一个JPanel中的所有页面,这可能吗? like this

1 个答案:

答案 0 :(得分:2)

如前所述,我需要在jframe中显示PDF文档的所有页面,因为我使用了org.apache.pdfbox.PDFReader,如下所示:

import java.awt.*;
import java.lang.reflect.*;
import java.util.List;

import javax.swing.*;

import org.apache.pdfbox.PDFReader;
import org.apache.pdfbox.pdfviewer.PageWrapper;
import org.apache.pdfbox.pdmodel.PDPage;

public class CustomPDFReader extends PDFReader {
/**
 * 
 */
private static final long serialVersionUID = 678451510308887925L;

public CustomPDFReader() {
    super();
}

public void setCurrentFile(String file) {
    try {
        Method m = getClass().getSuperclass().getDeclaredMethod("openPDFFile", 
                new Class<?>[]{String.class, String.class});
        m.setAccessible(true);
        m.invoke(this, file, null);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public static void main(String []args) {
    CustomPDFReader reader = new CustomPDFReader();
    // remove menubar
    JMenuBar menu = reader.getJMenuBar();
    menu.setVisible(false);

    JPanel header = new JPanel(new BorderLayout());

    JPanel firstLine = new JPanel();

    JLabel label = new JLabel("Label");
    firstLine.add(label);

    JPanel secondLine = new JPanel();

    JTextField text = new JTextField();
    text.setPreferredSize(new Dimension(100, 30));
    secondLine.add(text);

    JButton button = new JButton("Button");
    button.setPreferredSize(new Dimension(100, 30));
    secondLine.add(button);

    header.add(firstLine, java.awt.BorderLayout.NORTH);
    header.add(secondLine, java.awt.BorderLayout.SOUTH);

    reader.getContentPane().add(header, java.awt.BorderLayout.NORTH);

    // set default opened file
    reader.setCurrentFile("test.pdf");
    reader.showAllPages();
    reader.setVisible(true);
}

private void showAllPages() {
    try {
        Field pages = getClass().getSuperclass().getDeclaredField("pages");
        pages.setAccessible(true);
        List<PDPage> pagesList = (List<PDPage>) pages.get(this);

        Field documentPanel = getClass().getSuperclass().getDeclaredField("documentPanel");
        documentPanel.setAccessible(true);
        JPanel panel = (JPanel) documentPanel.get(this);
        panel.remove(0);
        GridLayout layout = new GridLayout(0, 1);
        panel.setLayout(layout);
        for(PDPage page : pagesList) {
            PageWrapper wrapper = new PageWrapper(this);
            wrapper.displayPage(page);
            panel.add(wrapper.getPanel());
        }
        pack();
    } catch(Exception e) {
        e.printStackTrace();
    }
}

}

PDFBox版本是1.8.10。您可以找到示例项目there