杰瑞科技汇

FlexPaper Java如何集成使用?

Of course! Here is a comprehensive guide to using FlexPaper with Java, covering what it is, how it works, and how to integrate it into a Java web application.

FlexPaper Java如何集成使用?-图1
(图片来源网络,侵删)

What is FlexPaper?

FlexPaper is an open-source (licensed under the Apache 2.0 license) viewer for converting PDF, DOC, DOCX, and other document formats into a web-based, interactive, and fast-loading page-turning experience.

Key Features:

  • Lightweight & Fast: Renders documents as vector-based SWF (Flash) or HTML5, making it much faster and lighter than embedding a full PDF plugin.
  • Cross-Platform: Works on all major web browsers.
  • Interactive: Includes features like zoom, search, print, page navigation, and a customizable toolbar.
  • Easy Integration: Designed to be easily embedded into any web application, including those built with Java (like Spring, Java EE, etc.).

Important Note: FlexPaper's primary rendering format is SWF (Flash). While it has an HTML5 renderer, it's a community-driven fork and may not be as robust or performant as the original SWF version. For new projects, consider if Flash is acceptable, or look for modern alternatives (see section 6).


How FlexPaper Works (The Architecture)

The process is a client-server model:

FlexPaper Java如何集成使用?-图2
(图片来源网络,侵删)
  1. Client-Side (Browser): The user's browser loads an HTML page that contains the FlexPaper viewer (a Flash .swf file).
  2. Server-Side (Java Application): The FlexPaper viewer makes an AJAX request to your Java server to get the document data.
  3. Conversion: Your Java application must first convert the source document (e.g., document.pdf) into a format FlexPaper can understand. The original FlexPaper uses SWF. This is typically done using a third-party tool like SWFTools.
  4. Serving: The Java application serves the converted SWF file and its corresponding XML definition file to the FlexPaper viewer.
  5. Rendering: The FlexPaper viewer loads the SWF and XML and displays the document with its page-turning interface.

Step-by-Step Integration Guide (Using SWF)

This guide assumes you are using a standard Java web project (e.g., with Maven) and a servlet container like Tomcat.

Step 1: Download and Prepare FlexPaper

  1. Download FlexPaper: Get the latest version from the official source or a trusted repository. A common source is Google Code (though it's archived) or GitHub mirrors.
    • Look for a package like FlexPaper_2.2.0.
  2. Extract the Archive: You will find several key files and folders.
    • FlexPaper.swf: The main viewer component.
    • js/: Contains the JavaScript loader (flexpaper_flash.js) and HTML examples.
    • assets/: May contain CSS and other assets.

Step 2: Set Up Your Java Web Project

  1. Create Project Structure: In your web application's src/main/webapp directory, create the following folders:

    webapp/
    ├── assets/          <-- For CSS, JS, images
    │   └── css/
    │       └── main.css
    ├── documents/       <-- To store your source and converted files
    │   ├── source/      <-- Original PDFs
    │   └── flexpaper/   <-- Converted SWF and XML files
    └── index.html      <-- The page that will host the viewer
  2. Copy FlexPaper Files:

    • Copy FlexPaper.swf into webapp/assets/.
    • Copy the contents of the js/ folder from the FlexPaper archive into webapp/assets/js/.

Step 3: Convert Your PDF to SWF (Using SWFTools)

This is a crucial external step. FlexPaper itself does not perform the conversion.

FlexPaper Java如何集成使用?-图3
(图片来源网络,侵删)
  1. Download SWFTools: Get the appropriate version for your OS from SWFTools official site.
  2. Install SWFTools: Follow the installation instructions for your system.
  3. Convert the PDF: Use the pdf2swf command-line tool. Open your terminal or command prompt and run:
    # Syntax: pdf2swf [input.pdf] -o [output.swf] -T 9 -f
    pdf2swf "C:/path/to/your/document.pdf" -o "C:/path/to/your/webapp/documents/flexpaper/document.swf" -T 9 -f
    • -T 9: Uses the latest SWF version for better quality.
    • -f: Forces the conversion even if it's imperfect.

Step 4: Create the HTML Page (index.html)

This page will load the FlexPaper viewer. Place it in webapp/index.html.

<!DOCTYPE html>
<html>
<head>FlexPaper Viewer</title>
    <link rel="stylesheet" href="assets/css/main.css" type="text/css"/>
    <script type="text/javascript" src="assets/js/jquery.min.js"></script>
    <script type="text/javascript" src="assets/js/flexpaper_flash.js"></script>
</head>
<body>
    <div id="documentViewer" style="width:100%; height:80vh;"></div>
    <script type="text/javascript">
        $(document).ready(function() {
            var config = {
                // The source file for the SWF
                'src': 'documents/flexpaper/document.pdf', 
                // The ID of the SWF object
                'swfFile': 'documents/flexpaper/document.swf', 
                // The location of the FlexPaper.swf file
                'playerPath': 'assets/FlexPaper.swf',
                // PDF navigation mode
                'pdfOpenParams': {
                    'viewMode': 'FitH',
                    'viewModeString': 'FitH',
                    'navpanes': 0,
                    'toolbar': 0,
                }
            };
            $('#documentViewer').flexPaperViewer(config);
        });
    </script>
</body>
</html>

Explanation:

  • swfFile: This is the path to the converted SWF file. This is what FlexPaper actually renders.
  • src: This is a bit of a legacy parameter, but it's good practice to include the original PDF path here. FlexPaper might use it for some operations.
  • playerPath: The path to the FlexPaper.swf viewer itself.
  • pdfOpenParams: Configuration for how the PDF should be displayed initially.

Step 5: Deploy and Run

  1. Deploy your Java web application to a server like Tomcat.
  2. Navigate to http://localhost:8080/your-app-name/index.html.
  3. You should see your document rendered with the FlexPaper interface!

Advanced Integration (Servlet for Dynamic Loading)

In a real application, you might not want to hardcode the file paths. You can use a Java servlet to dynamically provide the file path to the FlexPaper configuration.

  1. Create a Servlet:

    // File: DocumentServlet.java
    import java.io.IOException;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    @WebServlet("/config")
    public class DocumentServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // In a real app, you'd get this from a database or based on user input
            String documentName = "my-document";
            String swfPath = "documents/flexpaper/" + documentName + ".swf";
            // Return the configuration as JSON
            String config = String.format(
                "{ \"swfFile\": \"%s\", \"pdfFile\": \"%s.pdf\" }",
                swfPath, documentName
            );
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(config);
        }
    }
  2. Modify index.html to use the Servlet:

    <script type="text/javascript">
        $(document).ready(function() {
            $.getJSON('config', function(config) {
                var viewerConfig = {
                    'swfFile': config.swfFile,
                    'pdfFile': config.pdfFile,
                    'playerPath': 'assets/FlexPaper.swf',
                    'scale': 1.5,
                    'zoomTransition': 'easeOut',
                    'zoomTime': 0.5,
                    'zoomInterval': 0.2,
                    'fitPageOnLoad': true,
                    'fitWidthOnLoad': false,
                    'fullScreenAsMaxWindow': false,
                    'maxScale': 6,
                    'minScale': 0.2,
                    'searchMatch': 'true',
                    'printEnabled': true,
                    'printToolsVisible': true,
                    'showViewModeTools': true,
                    'showZoomTools': true,
                    'showFullScreenTools': true,
                    'showNavigationTools': true,
                    'showSearchTools': true,
                    'showDownloadTools': true
                };
                $('#documentViewer').flexPaperViewer(viewerConfig);
            });
        });
    </script>

Now, your FlexPaper viewer is dynamically configured by your Java backend.


Modern Alternatives to FlexPaper

Since FlexPaper relies on Flash (SWF), which is deprecated and not supported on mobile devices, it's worth considering modern alternatives for new Java projects.

  1. PDF.js (Mozilla):

    • How it works: A JavaScript library that renders PDFs using HTML5 Canvas without any plugins.
    • Java Integration: You can serve the PDF.js library and your PDF files from your Java application. It's pure client-side rendering.
    • Pros: Modern, no plugins, excellent mobile support, widely used.
    • Cons: Can be heavy for very large documents, rendering is not as "page-turning" as FlexPaper by default (though this can be customized).
  2. iText (for Server-Side Generation):

    • How it works: A powerful Java library for creating and manipulating PDFs. It doesn't create a web viewer, but you can use it to generate PDFs on the fly that are then viewed by the browser's native PDF plugin or downloaded.
    • Pros: Extremely powerful for server-side PDF manipulation.
    • Cons: Not a viewer. Relies on browser plugins for viewing, which FlexPaper was designed to avoid.
  3. Commercial Libraries (e.g., PDFTron, Datalogics):

    • How it works: These are high-end commercial SDKs that often provide both server-side processing and client-side JavaScript viewers.
    • Pros: Very robust, feature-rich, high performance, excellent support.
    • Cons: Expensive.

Summary

Feature FlexPaper (SWF) PDF.js Commercial Libraries
Technology Flash (SWF) HTML5 Canvas Proprietary
Browser Support Legacy (desktop only) Excellent (all modern) Excellent
Mobile Support Poor Excellent Excellent
Integration Simple (serve files) Simple (serve files) Complex (SDK)
Licensing Apache 2.0 (Open Source) Mozilla Public License (Open Source) Commercial
Best For Legacy systems or projects where Flash is acceptable. Recommended for most new projects. Enterprise applications with high demands.

For any new project, PDF.js is the most recommended modern alternative. If you must use FlexPaper, the guide above provides a solid foundation for getting it working with a Java backend.

分享:
扫描分享到社交APP
上一篇
下一篇