Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
104 views
in Technique[技术] by (71.8m points)

java - Basic code to display a pdf in an existing JPanel?

I have an existing interface that has a JPanel for displaying pdf files.

It is important to display the pdf inside this inteface and not open a new window. How can I display a pdf on the JPanel without using unnecessary code (libraries) if possible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

if you want to render PDF content and ignoring the orginal format (boldness, font size.. etc) you can parse PDF using any PDF parser(PDFBox, Tika .. etc) and then set the string result to any text Component (JTextFiled or JTextArea).

otherwise you should use PDF rendering library. there are some commercial libraries for that.

but there is small trick i was used in my last project to display PDF in my own panel, like this:

enter image description here

the idea is use embedded web component in your application , and then pass the file path to this component, then web rendering component will load the appropriate PDF rendering tool available in your machine, in my case the machine have acrobat reader.

i use this library Native Swing from DJ project: http://djproject.sourceforge.net/ns/

just make web browser:

private JWebBrowser fileBrowser = new JWebBrowser();

and control the browser appearance, then add the browser to your main panel ( its layout is BorderLayout)

fileBrowser.setBarsVisible(false);
fileBrowser.setStatusBarVisible(false);
fileRenderPanel.add(fileBrowser, BorderLayout.CENTER);

then if you to render PDF use:

fileBrowser.navigate(filePath);

if you want to highlight some keyword in the PDF:

fileBrowser.navigate(filePath + "#search= " + keyword + ""); // work on acrobat reader only

if you want to render other text (plain, html):

fileBrowser.setHTMLContent(htmlContent);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...