流式合并 PDF

    我正在寻找一个 Java PDF 合并解决方案,我可以在从 REST API 获取(来自 REST API 的示例)PDF 页面部分的同时流式传输合并的 pdf。伪代码应该是这样的:


public void doGet(HttpServletRequest req, HttpServletResponse res) throws Exception {


    sOut = res.getOutputStream();


    MergeDocument merger = MergeDocument.merge(sOut);


    for (int i = 0; i < 1000; i++) {


        byte[] contentPDF = restClient.get("http://mywebsite.com/files/mypdf"+i+".pdf");

        merger.append(contentPDF);

        sOut.flush(); // sending merged PDF bytes now

    }


    sOut.close();

}

我的观点是在开始将它发送给用户之前,不要浪费内存中所有 PDF 的堆内存。换句话说,当我从 rest 获得“contentBytes pdf”时,我现在想将它作为流媒体发送给用户。


希望可以有人帮帮我 :)


凤凰求蛊
浏览 131回答 1
1回答

收到一只叮咚

使用 itextpdfpackage com.example.demo.controller;import com.itextpdf.text.Document;import com.itextpdf.text.PageSize;import com.itextpdf.text.pdf.PdfCopy;import com.itextpdf.text.pdf.PdfReader;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.util.ArrayList;import java.util.List;import javax.servlet.http.HttpServletResponse;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestController@RequestMapping("/pdf")public class PdfMerger {&nbsp; @GetMapping&nbsp; public void merge(HttpServletResponse response) {&nbsp; &nbsp; Document document = new Document(PageSize.LETTER);&nbsp; &nbsp; response.setContentType("application/pdf");&nbsp; &nbsp; response.setHeader("Content-disposition", "attachment; filename=\"merged.pdf\"");&nbsp; &nbsp; OutputStream outputStream = null;&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; outputStream = response.getOutputStream();&nbsp; &nbsp; &nbsp; PdfCopy copy = new PdfCopy(document, outputStream);&nbsp; &nbsp; &nbsp; document.open();&nbsp; &nbsp; &nbsp; for (InputStream file : getPdfs()) {&nbsp; &nbsp; &nbsp; &nbsp; copy.addDocument(new PdfReader(file)); // writes directly to the output stream&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; outputStream.flush();&nbsp; &nbsp; } catch (Exception e) {&nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; } finally {&nbsp; &nbsp; &nbsp; if (document.isOpen()) {&nbsp; &nbsp; &nbsp; &nbsp; document.close();&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; if (outputStream != null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; outputStream.close();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; } catch (IOException ioe) {&nbsp; &nbsp; &nbsp; &nbsp; ioe.printStackTrace();&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; }&nbsp; private List<InputStream> getPdfs() {&nbsp; &nbsp; List<InputStream> list = new ArrayList<>();&nbsp; &nbsp; for (int i = 0; i < 10; i++){&nbsp; &nbsp; &nbsp; list.add(PdfMerger.class.getResourceAsStream("/pdf/1.pdf"));&nbsp; &nbsp; &nbsp; list.add(PdfMerger.class.getResourceAsStream("/pdf/2.pdf"));&nbsp; &nbsp; }&nbsp; &nbsp; return list;&nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java