网页动态获取并展示后台生成PDF文件流



    

1:前端通过pdfobject.js插件实现PDF文件的获取及展示。

      PDFObject.embed(URL, "#pdfDiv");

      URL可以为静态资源文件(如:./staticFiles/name.pdf),也可以为Servlet路径(如:getFileAction?name=name)

package com.kangping.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;

import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;

public class PrintMorePDF extends HttpServlet {
	@Override
	public void service(HttpServletRequest request, HttpServletResponse response) {
		try {
			request.setCharacterEncoding("utf-8");
			response.setCharacterEncoding("utf-8");
			PrintPDFs(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void PrintPDFs(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		String fileNames = request.getParameter("fileNames");
		if (null == fileNames) {
			response.getWriter().write("");
			return;
		}
		List streamOfPDFFiles = new ArrayList();
		JSONArray jsonArr = new JSONArray(fileNames);

		if (jsonArr.length() < 1) {
			response.getWriter().write("");
			return;
		}
		String notExistFileNames = "";
		for (int i = 0; i < jsonArr.length(); ++i) {
			File file = new File(jsonArr.getString(i));
			if (!file.exists()) {
				notExistFileNames += jsonArr.getString(i);
			}
		}
		if (notExistFileNames.length() > 1) {
			notExistFileNames = notExistFileNames.substring(0,
					notExistFileNames.length() - 1);
			response.getWriter().write(
					"");
			return;
		}
		for (int i = 0; i < jsonArr.length(); ++i) {
			InputStream in = new FileInputStream(jsonArr.getString(i));
			streamOfPDFFiles.add(in);
		}

		new PrintMorePDF().concatPDFs(streamOfPDFFiles, response
				.getOutputStream(), false);
	}

	public void concatPDFs(List streamOfPDFFiles,
			OutputStream outputStream, boolean paginate) {

		Document document = new Document();
		try {
			List pdfs = streamOfPDFFiles;
			List readers = new ArrayList();
			int totalPages = 0;
			Iterator iteratorPDFs = pdfs.iterator();

			// Create Readers for the pdfs.
			while (iteratorPDFs.hasNext()) {
				InputStream pdf = iteratorPDFs.next();
				PdfReader pdfReader = new PdfReader(pdf);
				readers.add(pdfReader);
				totalPages += pdfReader.getNumberOfPages();
			}
			// Create a writer for the outputstream
			PdfWriter writer = PdfWriter.getInstance(document, outputStream);

			document.open();
			BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA,
					BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
			PdfContentByte cb = writer.getDirectContent(); // Holds the PDF
			// data

			PdfImportedPage page;
			int currentPageNumber = 0;
			int pageOfCurrentReaderPDF = 0;
			Iterator iteratorPDFReader = readers.iterator();

			// Loop through the PDF files and add to the output.
			while (iteratorPDFReader.hasNext()) {
				PdfReader pdfReader = iteratorPDFReader.next();
				// Create a new page in the target for each source page.
				while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
					document.newPage();
					pageOfCurrentReaderPDF++;
					currentPageNumber++;
					page = writer.getImportedPage(pdfReader,
							pageOfCurrentReaderPDF);
					cb.addTemplate(page, 0, 0);

					// Code for pagination.
					if (paginate) {
						cb.beginText();
						cb.setFontAndSize(bf, 9);
						cb.showTextAligned(PdfContentByte.ALIGN_CENTER, ""
								+ currentPageNumber + " of " + totalPages, 520,
								5, 0);
						cb.endText();
					}
					/*
					 * pdfs.size() != 1 检测当前PDF总数大于1时才执行加页操作
					 */
					/*
					 * 检测到当前文档总页数为奇数页,则在最后一页的前一页加入空白页 使该文档成为偶数页文档,在打印时实现文档的分离
					 */
					/* if ((pageOfCurrentReaderPDF + 1) == pdfReader */
					/*
					 * 检测到当前文档总页数为奇数页,则在最后一页加入空白页 使该文档成为偶数页文档,在打印时实现文档的分离
					 */
					if (pdfs.size() > 1 && pageOfCurrentReaderPDF == pdfReader.getNumberOfPages()
							&& pdfReader.getNumberOfPages() % 2 == 1) {
						document.newPage();
						document.add(new Paragraph("     "));
					}
				}
				pageOfCurrentReaderPDF = 0;
			}
			outputStream.flush();
			document.close();
			outputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (document.isOpen())
				document.close();
			try {
				if (outputStream != null)
					outputStream.close();
			} catch (IOException ioe) {
				ioe.printStackTrace();
			}
		}
	}
}

2:后台用到了对文档操作的jar包。由于需求问题,此代码要将多份PDF文件合并成为一份PDF文件。

     思路是现申请一块内存,然后循环获取静态PDF文件,合并,再通过response的Outputstream将文件流发送到客户端。

3:前台PDF插件及后台的jar包点击这里https://download.csdn.net/download/qq_35392981/11389951

你可能感兴趣的:(PDF,前端)