11

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?

kleopatra
  • 51,061
  • 28
  • 99
  • 211
thewikus
  • 445
  • 1
  • 5
  • 16
  • 3
    Do you mean by using nothing but core Java? If so, then as far as I know, you can't. – Hovercraft Full Of Eels Mar 18 '12 at 19:58
  • Can you share any code (e.g. for this JPanel that displays pdf files)? Having that it would be easier to help you. From this brief introduction I could only suggest an approach similar to HTML frames where you can display more than one html document in one window. – aretai Mar 18 '12 at 20:25
  • Yes I would like to not use libraries as far as possible, because some open the pdf in a new window, and others create their own JPanel. I have a set size for the panel and a set location. Also if it is not possible, what library can I use to display the pdf in MY panel that is already created? How would the HTML frames help me, it sounds like a solution, but I don't know how it would work. – thewikus Mar 18 '12 at 21:18

4 Answers4

15

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);
Wajdy Essam
  • 4,280
  • 3
  • 28
  • 33
6

I think the best alternative is to use ICEpdf.

The ICEpdf API is 100% Java, lightweight, fast, efficient, and very easy to use.

ICEpdf can be used as standalone open source Java PDF viewer, or can be easily embedded in any Java application to seamlessly load or capture PDF documents. Beyond PDF document rendering, ICEpdf is extremely versatile, and can be used in a multitude of innovative ways.

In your project managed with Maven you could include:

<!-- 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>

Then, you could use a code similar to the following to visualize the pdf in a panel:

// 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());

As a result you could get something like the following:

Java Swing ICEpdf Viewer

Hope this can help you.

Sergio Sánchez Sánchez
  • 1,694
  • 3
  • 28
  • 48
  • Is there any way to copy text from displayed PDF? – Manikandan Raj Jul 17 '20 at 15:42
  • @Sergio I have tried with this solutions but i got error in `controller.getDocumentViewController()` and error is `The type org.icepdf.core.views.DocumentViewController cannot be resolved. It is indirectly referenced from required .class files`. I am using version 6.2.2.. can you please tell me how to resolve this error? – Akash Chavda Jul 23 '20 at 05:16
  • @Akash you had this error because of a corrupted local maven repository. So, in order to fix the problem, all you had to do was going in your repository and delete the folder where the concerned .jar was, then force an update maven in Eclipse – Sergio Sánchez Sánchez Jul 24 '20 at 14:35
  • @SergioSánchezSánchez Actually i am using latest jar file in desktop application and i have downloaded latest jar file from maven repository – Akash Chavda Jul 27 '20 at 07:26
1

You need to use a library to render it like jpedal or PDF-renderer or multivalent.

oers
  • 18,436
  • 13
  • 66
  • 75
mark stephens
  • 3,205
  • 16
  • 19
0

There is a very simple way with if you are willing to use SWT library. You are going to declare a Swing browser and set the browser URL to the path of the file.

    shell = new Shell();
    shell.setSize(800, 600);
    shell.setText("PDF View");
    
    Browser browser = new Browser(shell, SWT.NONE);
    browser.setUrl("sample.pdf");

    browser.setBounds(10, 10, 764, 541);

Here is the complete code:

import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

public class PdfViewPage {


protected Shell shell;
/**
 * Launch the application.
 * @param args
 */
public static void main(String[] args) {
    try {
        PdfViewPage window = new PdfViewPage();
        window.open();
        
    } catch (Exception e) {
        e.printStackTrace();
    }
}
/**
 * Open the window.
 */
public void open() {
    Display display = Display.getDefault();
    createContents();
    shell.open();
    shell.layout();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch()) {
            display.sleep();
        }
    }
}

/**
 * Create contents of the window.
 */
protected void createContents() {
    shell = new Shell();
    shell.setSize(800, 600);
    shell.setText("PDF View");
    
    Browser browser = new Browser(shell, SWT.NONE);
    browser.setUrl("sample.pdf");

    browser.setBounds(10, 10, 764, 541);

}
}
payhez
  • 27
  • 3