在JavaFX中显示pdf

在JavaFX中显示pdf,java,javafx,Java,Javafx,在JavaFX中开发桌面应用程序,需要显示pdf。我读到在JavaFX(当前版本)中不支持pdf查看/显示,我也读到了JPedal 现在,问题是: 是否有任何外部组件或库可以在JavaFX中查看pdf?它应该是一个免费软件 (如果必须使用JPedal)如何将其嵌入到应用程序中 JPedalFX示例代码和用法 随附了使用JPedalFX的示例代码 就我而言,这有点站不住脚,但我将在这里粘贴从JPedalFX库提供的示例查看器复制的代码片段示例代码。代码依赖于类路径(或应用程序jar清单中引用的库路

JavaFX
中开发桌面应用程序,需要显示pdf。我读到在
JavaFX
(当前版本)中不支持pdf查看/显示,我也读到了
JPedal

现在,问题是:

  • 是否有任何外部组件或库可以在JavaFX中查看pdf?它应该是一个免费软件
  • (如果必须使用
    JPedal
    )如何将其嵌入到应用程序中
    JPedalFX示例代码和用法

    随附了使用JPedalFX的示例代码

    就我而言,这有点站不住脚,但我将在这里粘贴从JPedalFX库提供的示例查看器复制的代码片段示例代码。代码依赖于类路径(或应用程序jar清单中引用的库路径)上的JPedalFX发行版附带的jpedal_lgpl.jar文件

    如果您对JPedalFX的使用有进一步的疑问,我建议您(他们过去一直在回复我)

    //获取文件路径。
    FileChooser fc=新建FileChooser();
    fc.setTitle(“打开PDF文件…”);
    fc.getExtensionFilters().add(新文件选择器.ExtensionFilter(“PDF文件”,“*.PDF”));
    文件f=fc.showOpenDialog(stage.getOwner());
    字符串文件名=file.getAbsolutePath();
    //打开文件。
    PdfDecoder pdf=新的PdfDecoder();
    openPdfFile(文件名);
    展示页(1);
    pdf.closePdfFile();
    . . . 
    /**
    *更新GUI以显示指定的页面。
    *@param页
    */
    专用无效显示页(整版页){
    //值机范围
    如果(页面>pdf.getPageCount())
    返回;
    如果(第<1页)
    返回;
    //贮藏
    页码=页码;
    //必要时显示/隐藏按钮
    如果(page==pdf.getPageCount())
    next.setVisible(false);
    其他的
    next.setVisible(true);
    如果(第==1页)
    back.setVisible(false);
    其他的
    back.setVisible(true);
    //计算比例
    int pW=pdf.getPdfPageData().getCropBoxWidth(第页);
    int pH=pdf.getPdfPageData().getCropBoxHeight(第页);
    维度s=Toolkit.getDefaultToolkit().getScreenSize();
    s、 宽度-=100;
    s、 高度-=100;
    双X刻度=(双)s.宽度/pW;
    双Y刻度=(双)s.高度/pH;
    双刻度=xScale
    SwingLabs PDF渲染器

    此外,我过去使用一个旧的基于SwingLabs Swing的pdf渲染器和JavaFX为我的应用程序渲染pdf。尽管在我开发浏览器时,Swing/JavaFX集成不是JavaFX的一个受支持的功能,但它对我来说仍然很好。集成代码位于和中


    请注意,Java 2.2和Java 8都支持这一点。

    JPedalFX示例代码和用法

    package de.vogella.itext.write;
    
    import java.io.FileOutputStream;
    import java.util.Date;
    
    import com.itextpdf.text.Anchor;
    import com.itextpdf.text.BadElementException;
    import com.itextpdf.text.BaseColor;
    import com.itextpdf.text.Chapter;
    import com.itextpdf.text.Document;
    import com.itextpdf.text.DocumentException;
    import com.itextpdf.text.Element;
    import com.itextpdf.text.Font;
    import com.itextpdf.text.List;
    import com.itextpdf.text.ListItem;
    import com.itextpdf.text.Paragraph;
    import com.itextpdf.text.Phrase;
    import com.itextpdf.text.Section;
    import com.itextpdf.text.pdf.PdfPCell;
    import com.itextpdf.text.pdf.PdfPTable;
    import com.itextpdf.text.pdf.PdfWriter;
    
    
    public class FirstPdf {
      private static String FILE = "c:/temp/FirstPdf.pdf";
      private static Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18,
          Font.BOLD);
      private static Font redFont = new Font(Font.FontFamily.TIMES_ROMAN, 12,
          Font.NORMAL, BaseColor.RED);
      private static Font subFont = new Font(Font.FontFamily.TIMES_ROMAN, 16,
          Font.BOLD);
      private static Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12,
          Font.BOLD);
    
      public static void main(String[] args) {
        try {
          Document document = new Document();
          PdfWriter.getInstance(document, new FileOutputStream(FILE));
          document.open();
          addMetaData(document);
          addTitlePage(document);
          addContent(document);
          document.close();
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    
      // iText allows to add metadata to the PDF which can be viewed in your Adobe
      // Reader
      // under File -> Properties
      private static void addMetaData(Document document) {
        document.addTitle("My first PDF");
        document.addSubject("Using iText");
        document.addKeywords("Java, PDF, iText");
        document.addAuthor("Lars Vogel");
        document.addCreator("Lars Vogel");
      }
    
      private static void addTitlePage(Document document)
          throws DocumentException {
        Paragraph preface = new Paragraph();
        // We add one empty line
        addEmptyLine(preface, 1);
        // Lets write a big header
        preface.add(new Paragraph("Title of the document", catFont));
    
        addEmptyLine(preface, 1);
        // Will create: Report generated by: _name, _date
        preface.add(new Paragraph("Report generated by: " + System.getProperty("user.name") + ", " + new Date(), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            smallBold));
        addEmptyLine(preface, 3);
        preface.add(new Paragraph("This document describes something which is very important ",
            smallBold));
    
        addEmptyLine(preface, 8);
    
        preface.add(new Paragraph("This document is a preliminary version and not subject to your license agreement or any other agreement with vogella.com ;-).",
            redFont));
    
        document.add(preface);
        // Start a new page
        document.newPage();
      }
    
      private static void addContent(Document document) throws DocumentException {
        Anchor anchor = new Anchor("First Chapter", catFont);
        anchor.setName("First Chapter");
    
        // Second parameter is the number of the chapter
        Chapter catPart = new Chapter(new Paragraph(anchor), 1);
    
        Paragraph subPara = new Paragraph("Subcategory 1", subFont);
        Section subCatPart = catPart.addSection(subPara);
        subCatPart.add(new Paragraph("Hello"));
    
        subPara = new Paragraph("Subcategory 2", subFont);
        subCatPart = catPart.addSection(subPara);
        subCatPart.add(new Paragraph("Paragraph 1"));
        subCatPart.add(new Paragraph("Paragraph 2"));
        subCatPart.add(new Paragraph("Paragraph 3"));
    
        // add a list
        createList(subCatPart);
        Paragraph paragraph = new Paragraph();
        addEmptyLine(paragraph, 5);
        subCatPart.add(paragraph);
    
        // add a table
        createTable(subCatPart);
    
        // now add all this to the document
        document.add(catPart);
    
        // Next section
        anchor = new Anchor("Second Chapter", catFont);
        anchor.setName("Second Chapter");
    
        // Second parameter is the number of the chapter
        catPart = new Chapter(new Paragraph(anchor), 1);
    
        subPara = new Paragraph("Subcategory", subFont);
        subCatPart = catPart.addSection(subPara);
        subCatPart.add(new Paragraph("This is a very important message"));
    
        // now add all this to the document
        document.add(catPart);
    
      }
    
      private static void createTable(Section subCatPart)
          throws BadElementException {
        PdfPTable table = new PdfPTable(3);
    
        // t.setBorderColor(BaseColor.GRAY);
        // t.setPadding(4);
        // t.setSpacing(4);
        // t.setBorderWidth(1);
    
        PdfPCell c1 = new PdfPCell(new Phrase("Table Header 1"));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);
    
        c1 = new PdfPCell(new Phrase("Table Header 2"));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);
    
        c1 = new PdfPCell(new Phrase("Table Header 3"));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);
        table.setHeaderRows(1);
    
        table.addCell("1.0");
        table.addCell("1.1");
        table.addCell("1.2");
        table.addCell("2.1");
        table.addCell("2.2");
        table.addCell("2.3");
    
        subCatPart.add(table);
    
      }
    
      private static void createList(Section subCatPart) {
        List list = new List(true, false, 10);
        list.add(new ListItem("First point"));
        list.add(new ListItem("Second point"));
        list.add(new ListItem("Third point"));
        subCatPart.add(list);
      }
    
      private static void addEmptyLine(Paragraph paragraph, int number) {
        for (int i = 0; i < number; i++) {
          paragraph.add(new Paragraph(" "));
        }
      }
    } 
    
    随附了使用JPedalFX的示例代码

    就我而言,这有点站不住脚,但我将在这里粘贴从JPedalFX库提供的示例查看器复制的代码片段示例代码。代码依赖于类路径(或应用程序jar清单中引用的库路径)上的JPedalFX发行版附带的jpedal_lgpl.jar文件

    如果您对JPedalFX的使用有进一步的疑问,我建议您(他们过去一直在回复我)

    //获取文件路径。
    FileChooser fc=新建FileChooser();
    fc.setTitle(“打开PDF文件…”);
    fc.getExtensionFilters().add(新文件选择器.ExtensionFilter(“PDF文件”,“*.PDF”));
    文件f=fc.showOpenDialog(stage.getOwner());
    字符串文件名=file.getAbsolutePath();
    //打开文件。
    PdfDecoder pdf=新的PdfDecoder();
    openPdfFile(文件名);
    展示页(1);
    pdf.closePdfFile();
    . . . 
    /**
    *更新GUI以显示指定的页面。
    *@param页
    */
    专用无效显示页(整版页){
    //值机范围
    如果(页面>pdf.getPageCount())
    返回;
    如果(第<1页)
    重新
    
    package de.vogella.itext.write;
    
    import java.io.FileOutputStream;
    import java.util.Date;
    
    import com.itextpdf.text.Anchor;
    import com.itextpdf.text.BadElementException;
    import com.itextpdf.text.BaseColor;
    import com.itextpdf.text.Chapter;
    import com.itextpdf.text.Document;
    import com.itextpdf.text.DocumentException;
    import com.itextpdf.text.Element;
    import com.itextpdf.text.Font;
    import com.itextpdf.text.List;
    import com.itextpdf.text.ListItem;
    import com.itextpdf.text.Paragraph;
    import com.itextpdf.text.Phrase;
    import com.itextpdf.text.Section;
    import com.itextpdf.text.pdf.PdfPCell;
    import com.itextpdf.text.pdf.PdfPTable;
    import com.itextpdf.text.pdf.PdfWriter;
    
    
    public class FirstPdf {
      private static String FILE = "c:/temp/FirstPdf.pdf";
      private static Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18,
          Font.BOLD);
      private static Font redFont = new Font(Font.FontFamily.TIMES_ROMAN, 12,
          Font.NORMAL, BaseColor.RED);
      private static Font subFont = new Font(Font.FontFamily.TIMES_ROMAN, 16,
          Font.BOLD);
      private static Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12,
          Font.BOLD);
    
      public static void main(String[] args) {
        try {
          Document document = new Document();
          PdfWriter.getInstance(document, new FileOutputStream(FILE));
          document.open();
          addMetaData(document);
          addTitlePage(document);
          addContent(document);
          document.close();
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    
      // iText allows to add metadata to the PDF which can be viewed in your Adobe
      // Reader
      // under File -> Properties
      private static void addMetaData(Document document) {
        document.addTitle("My first PDF");
        document.addSubject("Using iText");
        document.addKeywords("Java, PDF, iText");
        document.addAuthor("Lars Vogel");
        document.addCreator("Lars Vogel");
      }
    
      private static void addTitlePage(Document document)
          throws DocumentException {
        Paragraph preface = new Paragraph();
        // We add one empty line
        addEmptyLine(preface, 1);
        // Lets write a big header
        preface.add(new Paragraph("Title of the document", catFont));
    
        addEmptyLine(preface, 1);
        // Will create: Report generated by: _name, _date
        preface.add(new Paragraph("Report generated by: " + System.getProperty("user.name") + ", " + new Date(), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            smallBold));
        addEmptyLine(preface, 3);
        preface.add(new Paragraph("This document describes something which is very important ",
            smallBold));
    
        addEmptyLine(preface, 8);
    
        preface.add(new Paragraph("This document is a preliminary version and not subject to your license agreement or any other agreement with vogella.com ;-).",
            redFont));
    
        document.add(preface);
        // Start a new page
        document.newPage();
      }
    
      private static void addContent(Document document) throws DocumentException {
        Anchor anchor = new Anchor("First Chapter", catFont);
        anchor.setName("First Chapter");
    
        // Second parameter is the number of the chapter
        Chapter catPart = new Chapter(new Paragraph(anchor), 1);
    
        Paragraph subPara = new Paragraph("Subcategory 1", subFont);
        Section subCatPart = catPart.addSection(subPara);
        subCatPart.add(new Paragraph("Hello"));
    
        subPara = new Paragraph("Subcategory 2", subFont);
        subCatPart = catPart.addSection(subPara);
        subCatPart.add(new Paragraph("Paragraph 1"));
        subCatPart.add(new Paragraph("Paragraph 2"));
        subCatPart.add(new Paragraph("Paragraph 3"));
    
        // add a list
        createList(subCatPart);
        Paragraph paragraph = new Paragraph();
        addEmptyLine(paragraph, 5);
        subCatPart.add(paragraph);
    
        // add a table
        createTable(subCatPart);
    
        // now add all this to the document
        document.add(catPart);
    
        // Next section
        anchor = new Anchor("Second Chapter", catFont);
        anchor.setName("Second Chapter");
    
        // Second parameter is the number of the chapter
        catPart = new Chapter(new Paragraph(anchor), 1);
    
        subPara = new Paragraph("Subcategory", subFont);
        subCatPart = catPart.addSection(subPara);
        subCatPart.add(new Paragraph("This is a very important message"));
    
        // now add all this to the document
        document.add(catPart);
    
      }
    
      private static void createTable(Section subCatPart)
          throws BadElementException {
        PdfPTable table = new PdfPTable(3);
    
        // t.setBorderColor(BaseColor.GRAY);
        // t.setPadding(4);
        // t.setSpacing(4);
        // t.setBorderWidth(1);
    
        PdfPCell c1 = new PdfPCell(new Phrase("Table Header 1"));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);
    
        c1 = new PdfPCell(new Phrase("Table Header 2"));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);
    
        c1 = new PdfPCell(new Phrase("Table Header 3"));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);
        table.setHeaderRows(1);
    
        table.addCell("1.0");
        table.addCell("1.1");
        table.addCell("1.2");
        table.addCell("2.1");
        table.addCell("2.2");
        table.addCell("2.3");
    
        subCatPart.add(table);
    
      }
    
      private static void createList(Section subCatPart) {
        List list = new List(true, false, 10);
        list.add(new ListItem("First point"));
        list.add(new ListItem("Second point"));
        list.add(new ListItem("Third point"));
        subCatPart.add(list);
      }
    
      private static void addEmptyLine(Paragraph paragraph, int number) {
        for (int i = 0; i < number; i++) {
          paragraph.add(new Paragraph(" "));
        }
      }
    } 
    
    ├── pom.xml
    ├── src
    │   └── main
    │       ├── java
    │       │   └── me
    │       │       └── example
    │       │           ├── JSLogListener.java
    │       │           ├── Launcher.java
    │       │           └── WebController.java
    │       └── resources
    │           ├── build
    │           │   ├── pdf.js
    │           │   └── pdf.worker.js
    │           ├── main.fxml
    │           ├── web
    │           │   ├── cmaps
    │           │   ├── compatibility.js
    │           │   ├── debugger.js
    │           │   ├── images
    │           │   ├── l10n.js
    │           │   ├── locale
    │           │   ├── viewer.css
    │           │   ├── viewer.html
    │           │   └── viewer.js
    
    <?xml version="1.0" encoding="UTF-8"?>
    
    <?import javafx.scene.control.Button?>
    <?import javafx.scene.control.Tab?>
    <?import javafx.scene.control.TabPane?>
    <?import javafx.scene.layout.BorderPane?>
    <?import javafx.scene.web.WebView?>
    
    <BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="576.0" prefWidth="1024.0" xmlns="http://javafx.com/javafx/8.0.112" xmlns:fx="http://javafx.com/fxml/1" fx:controller="me.example.WebController">
        <center>
          <TabPane>
             <tabs>
                <Tab text="PDF test">
                   <content>
                        <WebView fx:id="web" minHeight="-1.0" minWidth="-1.0" />
                   </content>
                </Tab>
             </tabs>
          </TabPane>
        </center>
       <bottom>
          <Button fx:id="btn" mnemonicParsing="false" text="Open another file" BorderPane.alignment="CENTER" />
       </bottom>
    </BorderPane>
    
    var DEFAULT_URL = '';
    
    <head>
    
    <!-- ... -->
    <script src="viewer.js"></script>
    
    <!-- CUSTOM BLOCK -->
    <script>
        var openFileFromBase64 = function(data) {
            var arr = base64ToArrayBuffer(data);
            console.log(arr);
            PDFViewerApplication.open(arr);
        }
    
        function base64ToArrayBuffer(base64) {
          var binary_string = window.atob(base64);
          var len = binary_string.length;
          var bytes = new Uint8Array( len );
          for (var i = 0; i < len; i++)        {
              bytes[i] = binary_string.charCodeAt(i);
          }
          return bytes.buffer;
        }
    </script>
    <!-- end of CUSTOM BLOCK -->
    
    </head>
    
     public class WebController implements Initializable {
    
        @FXML
        private WebView web;
    
        @FXML
        private Button btn;
    
        public void initialize(URL location, ResourceBundle resources) {
            WebEngine engine = web.getEngine();
            String url = getClass().getResource("/web/viewer.html").toExternalForm();
    
            // connect CSS styles to customize pdf.js appearance
            engine.setUserStyleSheetLocation(getClass().getResource("/web.css").toExternalForm());
    
            engine.setJavaScriptEnabled(true);
            engine.load(url);
    
            engine.getLoadWorker()
                    .stateProperty()
                    .addListener((observable, oldValue, newValue) -> {
                        // to debug JS code by showing console.log() calls in IDE console
                        JSObject window = (JSObject) engine.executeScript("window");
                        window.setMember("java", new JSLogListener());
                        engine.executeScript("console.log = function(message){ java.log(message); };");
    
                        // this pdf file will be opened on application startup
                        if (newValue == Worker.State.SUCCEEDED) {
                            try {
                                // readFileToByteArray() comes from commons-io library
                                byte[] data = FileUtils.readFileToByteArray(new File("/path/to/file"));
                                String base64 = Base64.getEncoder().encodeToString(data);
                                // call JS function from Java code
                                engine.executeScript("openFileFromBase64('" + base64 + "')");
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
    
            // this file will be opened on button click
            btn.setOnAction(actionEvent -> {
                try {
                    byte[] data = FileUtils.readFileToByteArray(new File("/path/to/another/file"));
                    String base64 = Base64.getEncoder().encodeToString(data);
                    engine.executeScript("openFileFromBase64('" + base64 + "')");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
    }
    
    #toolbarViewerRight {
        display:none;
    }
    
    public class JSLogListener {
    
        public void log(String text) {
            System.out.println(text);
        }
    }
    
    public class Launcher extends Application {
    
        public static void main(String[] args) {
            Application.launch();
        }
    
        public void start(Stage primaryStage) throws Exception {
            Parent root = FXMLLoader.load(getClass().getResource("/main.fxml"));
            primaryStage.setTitle("PDF test app");
            primaryStage.setScene(new Scene(root, 1280, 576));
            primaryStage.show();
        }
    }