Waj*_*sam 14
如果你想渲染PDF内容并忽略原始格式(粗体,字体大小等),你可以使用任何PDF解析器(PDFBox,Tika ..等)解析PDF,然后将字符串结果设置为任何文本组件(JTextFiled或JTextArea中).
否则你应该使用PDF渲染库.有一些商业图书馆.
但是我在上一个项目中使用了一个小技巧来在我自己的面板中显示PDF,如下所示:

我们的想法是在您的应用程序中使用嵌入式Web组件,然后将文件路径传递给此组件,然后Web渲染组件将加载您机器中可用的相应PDF渲染工具,在我的情况下,该机器具有acrobat reader.
我使用这个来自DJ项目的Native Swing 库:http ://djproject.sourceforge.net/ns/
只需制作网页浏览器:
private JWebBrowser fileBrowser = new JWebBrowser();
Run Code Online (Sandbox Code Playgroud)
并控制浏览器外观,然后将浏览器添加到主面板(其布局为BorderLayout)
fileBrowser.setBarsVisible(false);
fileBrowser.setStatusBarVisible(false);
fileRenderPanel.add(fileBrowser, BorderLayout.CENTER);
Run Code Online (Sandbox Code Playgroud)
那么如果要渲染PDF使用:
fileBrowser.navigate(filePath);
Run Code Online (Sandbox Code Playgroud)
如果要在PDF中突出显示某些关键字:
fileBrowser.navigate(filePath + "#search= " + keyword + ""); // work on acrobat reader only
Run Code Online (Sandbox Code Playgroud)
如果你想渲染其他文本(plain,html):
fileBrowser.setHTMLContent(htmlContent);
Run Code Online (Sandbox Code Playgroud)
我认为最好的选择是使用ICEpdf。
ICEpdf API 是 100% Java,轻量级、快速、高效且非常易于使用。
ICEpdf 可以用作独立的开源 Java PDF 查看器,也可以轻松嵌入到任何 Java 应用程序中以无缝加载或捕获 PDF 文档。除了 PDF 文档渲染之外,ICEpdf 的用途极其广泛,并且可以以多种创新方式使用。
在使用 Maven 管理的项目中,您可以包括:
<!-- https://mvnrepository.com/artifact/org.icepdf.os/icepdf-core -->
<dependency>
<groupId>org.icepdf.os</groupId>
<artifactId>icepdf-core</artifactId>
<version>${icepdf.version}</version>
<exclusions>
<exclusion>
<groupId>javax.media</groupId>
<artifactId>jai_core</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- https://mvnrepository.com/artifact/org.icepdf.os/icepdf-viewer -->
<dependency>
<groupId>org.icepdf.os</groupId>
<artifactId>icepdf-viewer</artifactId>
<version>${icepdf.version}</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用类似于以下的代码在面板中可视化 pdf:
// Instance the controller
controller = new SwingController();
// We created the SwingViewFactory configured with the controller
SwingViewBuilder factory = new SwingViewBuilder(controller);
// We use the factory to build a preconfigured JPanel
// with a full and active viewer user interface.
viewerComponentPanel = factory.buildViewerPanel();
viewerComponentPanel.setPreferredSize(new Dimension(400, 243));
viewerComponentPanel.setMaximumSize(new Dimension(400, 243));
// We add keyboard command
ComponentKeyBinding.install(controller, viewerComponentPanel);
// add interactive mouse link annotation support via callback
controller.getDocumentViewController().setAnnotationCallback(
new org.icepdf.ri.common.MyAnnotationCallback(
controller.getDocumentViewController()));
// We add the component to visualize the report
reportViewerContainer.add(viewerComponentPanel, BorderLayout.CENTER);
reportViewerContainer.invalidate();
// We open the generated document
controller.openDocument(reportLocationUri.toURL());
Run Code Online (Sandbox Code Playgroud)
结果你可能会得到类似下面的东西:
希望这可以帮到你。
| 归档时间: |
|
| 查看次数: |
18506 次 |
| 最近记录: |