【问题标题】:How to convert a PDF generating in response.outputStream to a Base64 encoding如何将在 response.outputStream 中生成的 PDF 转换为 Base64 编码
【发布时间】:2014-12-13 08:55:59
【问题描述】:

我正在做一个项目,我需要为参加考试的学生创建一张录取卡。 pdf 生成部分工作正常,但我的问题是我必须将我的 pdf 编码为 Base64 格式。我没有找到任何解决方案。我的代码如下所示

   public void downloadPdf() throws IOException, DocumentException {
            System.out.println("hi i ma in");    
            resultList=examinationDetailsService.readAdmitCardData();

            for(Object[]  data:resultList)
            {
                personalDetails=(PersonalDetails)data[0];
                System.out.println("name"+personalDetails.getApplicantName());
                rollNoAssign=(RollNoAssign)data[1];
                System.out.println("rollno"+rollNoAssign.getRollNo());
                examDateAssign=(ExamDateAssign)data[2];
            }
            //Converting Date
             SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd-MM-yyyy");
             String date = DATE_FORMAT.format(examDateAssign.getExaminationDate());
            // Get the FacesContext
            FacesContext facesContext = FacesContext.getCurrentInstance();
            // Get HTTP response
            HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
            // Set response headers
            response.reset();   // Reset the response in the first place
            response.setHeader("Content-Type", "application/pdf");  // Set only the content type
             // Open response output stream
            OutputStream responseOutputStream = response.getOutputStream();

            Document document = new Document(PageSize.A4, 0, 0, 0, 0);
            PdfWriter.getInstance(document,response.getOutputStream());
            document.open();
            PdfPTable maintable = new PdfPTable(1);
            maintable.setWidthPercentage(90);
            maintable.setSpacingBefore(0f);
            maintable.setSpacingAfter(0f);
            Paragraph ph1 = new Paragraph();
            ph1.add(new Chunk("\n\nGOVERNMENT OF ASSAM \nOFFICE OF THE ELECTRICAL LICENSING BOARD, ASSAM\n1", FontFactory.getFont(FontFactory.TIMES_ROMAN, 12, Font.NORMAL)));
            //ph1.add(new Chunk("ST", FontFactory.getFont(FontFactory.TIMES_ROMAN, 12, Font.NORMAL)));
            Chunk superScript = new Chunk("ST", FontFactory.getFont(FontFactory.TIMES_ROMAN, 8, Font.NORMAL));
            superScript.setTextRise(5f);
            ph1.add(superScript);
            ph1.add(new Chunk(" FLOOR, WEST END BLOCK, HOUSEFED COMPLEX,DISPUR, GUWAHATI-781006, ASSAM.", FontFactory.getFont(FontFactory.TIMES_ROMAN, 12, Font.NORMAL)));
            ph1.add(new Chunk("\n***\n", FontFactory.getFont(FontFactory.TIMES_ROMAN, 12, Font.BOLD)));
            ph1.add(new Chunk("\nADMIT CARD", FontFactory.getFont(FontFactory.TIMES_ROMAN, 12, Font.BOLD)));

            PdfPCell heading1 = new PdfPCell(ph1);
            heading1.setBorder(0);
            heading1.setHorizontalAlignment(Element.ALIGN_CENTER);
            heading1.setVerticalAlignment(Element.ALIGN_CENTER);
            maintable.addCell(heading1);

            PdfPTable maintable1 = new PdfPTable(1);
            maintable1.setWidthPercentage(87);
            maintable1.setSpacingBefore(0f);
            maintable1.setSpacingAfter(0f);

            Paragraph ph2 = new Paragraph();
            ph2.add(new Chunk("\n\nShri/Smti "+personalDetails.getApplicantName()+", Roll No. "+rollNoAssign.getRollNo()+" is hereby "
                    + "allowed to appear in the examination for grant of Electrical Supervisor's Certificate of Competency "
                    + "to be held at "+ rollNoAssign.getVenue().getName()
                    + "as per schedule given below:", FontFactory.getFont(FontFactory.TIMES_ROMAN, 11, Font.NORMAL)));
            ph2.add(new Chunk("\n\n          Viva-voce", FontFactory.getFont(FontFactory.TIMES_ROMAN, 11, Font.BOLD)));
            ph2.add(new Chunk(" test on "+date+ " at 9 AM/12.30 PM ;", FontFactory.getFont(FontFactory.TIMES_ROMAN, 11, Font.NORMAL)));
            ph2.add(new Chunk(" Written", FontFactory.getFont(FontFactory.TIMES_ROMAN, 11, Font.BOLD)));
            ph2.add(new Chunk(" test on __________ at 9 AM.", FontFactory.getFont(FontFactory.TIMES_ROMAN, 11, Font.NORMAL)));
            ph2.add(new Chunk("\n\n\nPlease bring the followings with you while coming for the said examinations:                               \n"
                    + "\n1.Original copy of Degree/Diploma/ITI Certificate/Supervisor's Certificate of Competency/"
                    + "Workmen's Permit\n\n    belonging to you and this Admit Card in original.\n"
                    + "\n2.Detail experience certificate(s) relevant to the part(s) of Supervisor's examination applied for.\n"
                    + "\n3.\n"
                    + "\n\nNB:  (a)   No alteration is allowed in the entries on this Admit Card without the authority of the Board."
                    + "\n         (b)  No expense(s) incurred by any candidate will be borne by the Board.\n\n\n", FontFactory.getFont(FontFactory.TIMES_ROMAN, 11, Font.NORMAL)));
            PdfPCell heading2 = new PdfPCell(ph2);
            heading2.setBorder(0);
            heading2.setHorizontalAlignment(Element.ALIGN_JUSTIFIED);
            heading2.setVerticalAlignment(Element.ALIGN_CENTER);
            maintable1.addCell(heading2);

            PdfPTable maintable2 = new PdfPTable(2);
            float[] columnWidths = new float[]{55f, 45f};
            maintable2.setWidths(columnWidths);
            maintable2.setWidthPercentage(84);
            maintable2.setSpacingBefore(0f);
            maintable2.setSpacingAfter(0f);

            Paragraph ph31 = new Paragraph();
            ph31.add(new Chunk("Details furnished by you in the application form and/or examination process are used by the Board"
                    + " for further needful, hence, if you feel any correction(s) in the same is/are required, please get those done before"
                    + " leaving the examination venue. The Board shall not be under any obligation of removing the difficulties arising later"
                    + " on out of incorrect/improper information furnished by you or non-furnishing of required ones.\n", FontFactory.getFont(FontFactory.COURIER, 10, Font.NORMAL)));
            PdfPCell heading31 = new PdfPCell(ph31);
            heading31.setBorder(15);
            heading31.setHorizontalAlignment(Element.ALIGN_JUSTIFIED);
            heading31.setVerticalAlignment(Element.ALIGN_LEFT);

            maintable2.addCell(heading31);

            Paragraph ph32 = new Paragraph();
            ph32.add(new Chunk("\n\n\n(Member Secretary)\nElectrical Licensing Board,\nAssam.", FontFactory.getFont(FontFactory.TIMES_ROMAN, 12, Font.NORMAL)));
            PdfPCell heading32 = new PdfPCell(ph32);
            heading32.setBorder(0);
            heading32.setHorizontalAlignment(Element.ALIGN_CENTER);
            heading32.setVerticalAlignment(Element.ALIGN_CENTER);
            maintable2.addCell(heading32);

            document.add(maintable);
            document.add(maintable1);
            document.add(maintable2);
            document.close();

           /* // Read PDF contents
            URL url = new URL(PDF_URL);
            InputStream pdfInputStream = url.openStream();*/

            // Read PDF contents and write them to the output
            byte[] bytesBuffer = new byte[2048];
            int bytesRead;
           /* while ((bytesRead = pdfInputStream.read(bytesBuffer)) > 0) {
                responseOutputStream.write(bytesBuffer, 0, bytesRead);
            }
            */
            Base64 encoder = new Base64();
            byte[] decodedBytes = encoder.o

            // Make sure that everything is out
            responseOutputStream.write(decodedBytes);
            responseOutputStream.flush();

            // Close both streams
            //pdfInputStream.close();
            responseOutputStream.close();

            // JSF doc:
            // Signal the JavaServer Faces implementation that the HTTP response for this request has already been generated
            // (such as an HTTP redirect), and that the request processing lifecycle should be terminated
            // as soon as the current phase is completed.
            facesContext.responseComplete();

        }

请给我任何解决方案。我用的是itext

【问题讨论】:

    标签: pdf base64 itext


    【解决方案1】:

    当我查看您的代码时,我看到了:

    PdfWriter.getInstance(document,response.getOutputStream());
    

    这意味着您正在指示 iText 将 PDF 字节直接写入浏览器。此输出流在您关闭文档时关闭。

    我也看到了:

    OutputStream responseOutputStream = response.getOutputStream();
    

    我什至看到您尝试向此流中添加内容。这是不可能的,因为流已经关闭。

    你需要像这样创建一个ByteArrayOutputStream

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    

    并在PdfWriter中使用它:

    PdfWriter.getInstance(document, baos);
    

    现在您可以像这样获取 PDF 字节:

    byte[] pdf = baos.toByteArray();
    

    现在您可以对这些字节进行编码并将它们发送到输出流。

    编码:

    假设您使用org.apache.commons.codec.binary.Base64,如Base64 Encoding in Java 的回答中所述,您可以这样做:

    byte[] base64 = Base64.encodeBase64(pdf);
    

    (还有其他方法可以做到这一点。)

    发送到输出流:

    response.setHeader("Expires", "0");
    response.setHeader("Cache-Control",
                "must-revalidate, post-check=0, pre-check=0");
    response.setHeader("Pragma", "public");
    response.setContentType("application/pdf");
    response.setContentLength(base64.length);
    OutputStream os = response.getOutputStream();
    os.write(base64);
    os.flush();
    os.close();
    

    【讨论】:

    • 本来打算写长一点的答案,但是没有时间细说,所以很高兴看到我的答案足以解决问题。
    • Bruno Lowagie 请更新它,因为我需要将 pdf 与 web 服务一起使用
    • 谢谢 Bruno Lowagie。我会试试你的代码。我的问题是-2。所以请通过给它一个赞来改进它,以便其他人可以从中受益
    猜你喜欢
    • 1970-01-01
    • 2019-02-16
    • 2012-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-27
    • 1970-01-01
    • 2019-07-28
    相关资源
    最近更新 更多