Dynamic PDF Online Preview

Source: Internet
Author: User
Tags pdfobject

Live dynamic PDF Online Preview and PDF file conversion with signature

Opening words:

Recently work needs to make a loan contract, the company's previous contracts are downloaded through the app side, and then open the PDF file locally, and like the innovation of me, thinking why not online H5 preview, it is this idea, said dry, the practice process is always difficult, tossing a 3, 4 days of time, boil two early morning 3, 4 o'clock, one of the hardships, as well as the twists and turns, the pressure only oneself can experience, the project on-line after thinking I want to write a blog post, one is to summarize the experience, followed by sharing their own this way to the experience, welcome to spit Groove! , do not say a lot of nonsense, to some dry goods!

PDF Online Preview implementation:

8 Implementation of the online Browse PDF file Utility Plug-in, the author chooses Pdf.js, the following simple introduction 8 plugins:

Pdfobject

Pdfobject can help you embed PDF files directly on the page, and sometimes some projects need to embed PDF files dynamically. Pdfobject For this purpose, he is able to embed PDF files quickly and easily, pdfobject use JavaScript to produce the same standards-compliant markup, and then insert the selection into your HTML elements. You can fill the entire browser window, or convert the PDF format to one or other block-level elements.

Pdf.js

Unlike the closed source PDF Browsing plugin that Google Chrome uses from Foxit, Pdf.js is an open source product based on open HTML5 and JavaScript technology .

Pdf.js is a small plug-in that is primarily used to read PDF documents online on the HTML5 platform, written on JavaScript-based technology without any local technical support.

Pdf.js was released by Mozilla Labs. Their goal is to create a common, standards-based web platform that can parse and render PDF files and eventually publish a PDF reader extension, without a doubt pdf.js will be integrated into Gecko as an embedded PDF reader for Firefox, but the specific integration schedule has not yet been determined

Jspdf

Jspdf is an open source library that generates PDFs using JavaScript language. You can use it in Firefox plugins, server-side scripts, or browser scripts. Client Safari and IPhone Safari support the best, followed by opera and Windows Firefox 3 and so on. IE temporarily does not support:

JQuery Media Plugin

jquery Media plugin is a jquery-based web Media Player plugin that supports most network multimedia players and multimedia formats such as: Flash, Windows Media Player, Real Player, Quicktime, Mp3,silverlight, PDF. Based on the current script configuration, it automatically replaces the a tag with a DIV and generates an object, embed, or even an IFRAME code, as to whether the generated object or Embed,jquery media will automatically discriminate based on the current platform. So the compatibility aspect is excellent. The following code is generated by jquery media.

Google Docs PDF Viewer

ZOHO Viewer

Anychart: Exporting PDFs using JavaScript

You can export a static image or an embedded still image in PNG or JPG format, a chart or a fully interactive function diagram

JQuery Document Viewer

The document viewer is a jquery plugin that allows you to view multiple file formats directly in a Web page. Document Browser supported file formats: PDF files, text files, code, images, audio, video, etc.

Pdf.js Practice Chapter

  The first step pdf.js source download Https://github.com/mozilla/pdf.js

The source page has a detailed compilation step-up, and finally compiled, the generic file copy to the Tomcat WebApps directory, browser input http://localhost:8080/generic/web/viewer.html,H5 preview effect as follows, The picture is compressed, the actual preview effect is much better

(I've covered the Webapps\generic\web\compressed.tracemonkey-pldi-09.pdf file, which comes with an English document):

  The second step I integrated into the project in the form of a plugin directory structure is as follows:

The third step: write the H5 file, here is the Pdf.js viever.html page through the Ifram embedded, and by specifying the file parameter dynamic parameters, to achieve dynamic PDF file Preview

LOANPDFCONTRACT.JSP:

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%>

<%@ taglib prefix= "C" uri= "Http://java.sun.com/jsp/jstl/core"%>
<! DOCTYPE html>
<meta charset= "UTF-8"/>
<meta name= "viewport" content= "width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0, User-scalable=no "/>
<meta name= "apple-mobile-web-app-capable" content= "yes"/>
<meta name= "Apple-mobile-web-app-status-bar-style" content= "Black"/>
<meta name= "format-detection" content= "Telephone=no,email=no,address=no"/>
<title> Loan Contract </title>
<body>
<iframe src= "<c:url value="/plugin/pdfjs/generic/web/viewer.html "/>?file=<c:url value="/app/credit/ Loanapplication/contracts/${fileid} "/>"
Width= "100%" height= ">"
</iframe>
</body>
Fourth Step: Write the Controller method,
/** 
* 16. Loan application [information confirmation] contract and related agreement-loan contract H5 interface provided to the app side call
*
* @param userId
* @return
* @since 3.4
*/< br> @RequestMapping (value = "/app/credit/loanapplication/contracts/loancontract.security")
Public Object Loancontract (String userid,string borrowcode,string Producttypecode, model model) {
if (Stringutils.isempty (userId ) || Stringutils.isempty (borrowcode) {
return "app/credit/canaloanapplication/404error";
}
Map<string,string> Returnmap = canaapplyloanservice.investmentcontracttemplate (UserId,borrowCode, Producttypecode);
if (BizCodeType.IS_NO.getCode (). Equals (Returnmap.get ("flag"))) {
Return "App/credit/canaloanapplication/40 4Error ";
}
Model.addattribute ("FileId", Returnmap.get ("fileId") + ". pdf");
return "App/credit/canaloanapplication/loanpdfcontract";
}

  
Fifth step: Write the Controller method, note that this HTTP head response header information set is httpstatus.ok, and file download httpstatus.create header information is different.

/**

* View PDF file
* @param fileId
* @return
* @throws IOException
*/
@RequestMapping (value = "/app/credit/loanapplication/contracts/{fileid}.pdf", method = Requestmethod.get)
Public responseentity<byte[]> loadcontract (@PathVariable String fileId) throws IOException {
Byte[] Bytes=canaapplyloanservice.downcontract (fileId);
Final Httpheaders headers = new Httpheaders ();
Headers.setcontenttype (mediatype.valueof ("application/pdf"));
Headers.setcontentlength (bytes.length);
Headers.add (httpheaders.accept_ranges, "bytes");
return new responseentity<byte[]> (bytes, headers, Httpstatus.ok);
}

Concluding remarks here, PDF file online Dynamic Preview to complete the basic, quickly experience it!

Advanced article: Java implementation pdf file to picture, multiple picture synthesis PDF file .

Preface:

    Because the author of the PDF file here with interactive form fields, resulting in PDF files can not be previewed, because it is a contract PDF file, the knock with signature information caused the PDF preview failed, was very confused, no direction, and later and the same city golden suit an architect friend chat, he gave me a hint, "said is the question of signature, Need to turn the PDF into a picture, for the author, with the idea that the rest is the practice of things.

Because the PDF has more than one page so it will be transferred out of many pictures, as to why to turn into a picture, just to take out the interactive form of the signature to kill, because the author used to do too many pictures to synthesize a large picture, so at the time, I thought, this multiple images to synthesize a PDF file should not be a problem, For me who used to play PDF files Less, this idea has been very bold, if the reader you also do not know the depth of the PDF file, then this article will be very suitable for you, with your actual combat pdf!

I am wordy, because this PDF file signature causes the app side to not be able to view because it is a third party contract company, so we need their signature SDK file to preview,

First article: Take you to pack B, take you to fly!

Say so much, do not have a bit of dry goods I'm afraid you can not see, the mainstream of the PDF and the image of the transfer

1.PDFRenderer: The most efficient, but the lack of font support for most of the Chinese PDF can not be processed, the author began to use a bit, but the error later gave up.

2.jpedal: This is a commercial version, its official website of the jar download is slow, the beginning originally intended to use, finally csdn down the next jar package, a run hint jar package expired.

3.pdfbox: I finally adopt pdfbox, the effect is good. Before online said it to Chinese support is not good, but the author in Pdfbox_2.0.2.jar use process did not meet garbled.

Article Two: PDFBox use

maven Configuration:

<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.2</version>
</dependency>


Java code:

  

Import org.apache.pdfbox.pdmodel.PDDocument;
Import Org.apache.pdfbox.pdmodel.PDPage;
Import Org.apache.pdfbox.pdmodel.PDPageContentStream;
Import Org.apache.pdfbox.pdmodel.common.PDRectangle;
Import Org.apache.pdfbox.pdmodel.graphics.image.JPEGFactory;
Import Org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
Import Org.apache.pdfbox.rendering.PDFRenderer;

Import Javax.imageio.ImageIO;
Import java.awt.*;
Import Java.awt.geom.AffineTransform;
Import Java.awt.image.BufferedImage;
Import Java.awt.image.ColorModel;
Import Java.awt.image.WritableRaster;
Import java.io.*;
Import java.util.ArrayList;
Import java.util.List;

public class Pdfboxutil {

public static void Main (string[] args) {
Pdftoimg ("D:\\test\\22222.pdf", "d:\\test\\22222.png");
Pdftoimgtopdf ("D:\\test\\22222.pdf", "d:\\test\\3333.pdf");
}

/**
* PDF to Image
* @param Pdfpath
* @param Pngpath
*/
public static void Pdftoimg (String pdfpath,string pngpath) {
Put a PDF picture and customize the image to a format size
File File = new file (Pdfpath);
try {
PDDocument doc = pddocument.load (file);
Pdfrenderer renderer = new Pdfrenderer (DOC);
int pagecount = Doc.getnumberofpages ();
for (int i = 0; i < PageCount; i++) {
BufferedImage image = renderer.renderimagewithdpi (i, 240);
BufferedImage Srcimage = Resize (image, Image.getwidth (), Image.getheight ());
Imageio.write (Srcimage, "PNG", New File (Pngpath.replace (".", i+ "."));
}
} catch (IOException e) {
E.printstacktrace ();
}
}
/**
* PDF to picture then synthesize PDF
* @param Pdfpath
* @param Pdfoutpath
*/
public static void Pdftoimgtopdf (String pdfpath,string pdfoutpath) {
Put a PDF picture and customize the image to a format size
File File = new file (Pdfpath);
try {
PDDocument doc = pddocument.load (file);
Pdfrenderer renderer = new Pdfrenderer (DOC);
int pagecount = Doc.getnumberofpages ();
List<bufferedimage> images=new arraylist<bufferedimage> ();
for (int i = 0; i < PageCount; i++) {
BufferedImage image = renderer.renderimagewithdpi (i, 240);
BufferedImage Srcimage = Resize (image, Image.getwidth (), Image.getheight ());
Images.add (Srcimage);
}
Synthesizing pictures to PDF
Createpdffromimage (pdfoutpath,images);
} catch (IOException e) {
E.printstacktrace ();
}
}
/**
* PDF to picture then synthesize PDF
* @param input
*/
public static byte[] Pdftoimgtopdf (byte[] input) {
Put a PDF picture and customize the image to a format size
Byte[] Bytes=null;
PDDocument Doc=null;
try {
doc = pddocument.load (input);
List<bufferedimage> images=new arraylist<bufferedimage> ();
Pdfrenderer renderer = new Pdfrenderer (DOC);
int pagecount = Doc.getnumberofpages ();
for (int i = 0; i < PageCount; i++) {
BufferedImage image = renderer.renderimagewithdpi (i, 240);
BufferedImage Srcimage = Resize (image, Image.getwidth (), Image.getheight ());
Images.add (Srcimage);
}
Bytes=createpdffromimage (images);
} catch (IOException e) {
E.printstacktrace ();
}
if (doc!=null) {
try {
Doc.close ();
} catch (IOException e) {
E.printstacktrace ();
}
}
return bytes;
}
/**
* Image synthesis PDF
* @param images
* @throws Exception
*/
public static void Createpdffromimage (String pdfoutpath,list<bufferedimage> images) {
PDDocument doc = new pddocument ();
try {
Pdpagecontentstream Contentstream;
Pdpage page;
for (BufferedImage image:images) {
page = new Pdpage (New Pdrectangle (Image.getwidth (), Image.getheight ()));
Doc.addpage (page);
Contentstream = new Pdpagecontentstream (Doc,page,pdpagecontentstream.appendmode.append, true);
Pdimagexobject pdimagexobject = Jpegfactory.createfromimage (doc,image);
Contentstream.drawxobject (pdimagexobject, 0, 0, image.getwidth (), Image.getheight ());
Contentstream.close ();
}
Doc.save (Pdfoutpath);
}catch (Exception ex) {
Ex.printstacktrace ();
}finally {
if (doc! = null) {
try {
Doc.close ();
} catch (IOException e) {
E.printstacktrace ();
}
}
}
}
/**
* Image synthesis PDF
* @param images
* @throws Exception
*/
public static byte[] Createpdffromimage (list<bufferedimage> images) {
Byte[] Bytes=null;
Bytearrayoutputstream Baos=null;
PDDocument doc = new pddocument ();
try {
Pdpagecontentstream Contentstream;
Pdpage page;
for (BufferedImage image:images) {
page = new Pdpage (New Pdrectangle (Image.getwidth (), Image.getheight ()));
Doc.addpage (page);
Contentstream = new Pdpagecontentstream (Doc,page,pdpagecontentstream.appendmode.append, true);
Pdimagexobject pdimagexobject = Jpegfactory.createfromimage (doc,image);
Contentstream.drawxobject (pdimagexobject, 0, 0, image.getwidth (), Image.getheight ());
Contentstream.close ();
}
BAOs = new Bytearrayoutputstream ();
Doc.save (BAOs);
Bytes=baos.tobytearray ();
}catch (Exception ex) {
Ex.printstacktrace ();
}finally {
if (BAOs! = null) {
try {
Baos.close ();
} catch (IOException e) {
E.printstacktrace ();
}
}
if (doc! = null) {
try {
Doc.close ();
} catch (IOException e) {
E.printstacktrace ();
}
}
}
return bytes;
}
/**
* Create picture
* @param source
* @param TARGETW
* @param targeth
* @return
*/
private static BufferedImage Resize (bufferedimage source, int targetw, int targeth) {
int type = Source.gettype ();
BufferedImage target = null;
Double SX = (double) targetw/source.getwidth ();
Double sy = (double) targeth/source.getheight ();
if (SX > Sy) {
SX = SY;
TARGETW = (int) (SX * SOURCE.GETWIDTH ());
} else {
SY = SX;
Targeth = (int) (SY * source.getheight ());
}
if (type = = Bufferedimage.type_custom) {
ColorModel cm = Source.getcolormodel ();
WritableRaster raster = Cm.createcompatiblewritableraster (TARGETW, Targeth);
Boolean alphapremultiplied = Cm.isalphapremultiplied ();
target = new BufferedImage (cm, raster, alphapremultiplied, null);
} else {
target = new BufferedImage (TARGETW, Targeth, type);
}
Graphics2D g = target.creategraphics ();
G.setrenderinghint (renderinghints.key_rendering, renderinghints.value_render_quality);
G.drawrenderedimage (source, affinetransform.getscaleinstance (SX, SY));
G.dispose ();
return target;
}

}

Summary language:

Here I have to say goodbye to you, basically will I three days of research of all the results of the contribution, one of the hardships, carried over how many pits, you may not know, I can only tell you, most of the time my heart is dashed!

Remarks Pdf.js My project plug-in source code can be to my Baidu Cloud Extract link: http://pan.baidu.com/s/1c2JVe1M Password: K9SC

If you are having trouble with the use of the process, you can send me an email, [email protected]

Dynamic PDF Online Preview

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.