Почему скачанный файл pdf bij Trinidad FileDownloadActionListener не может быть открыт с помощью программы чтения pdf? - PullRequest
0 голосов
/ 17 июня 2020

Я создаю PDF из String, который этот String находится в xml format, и представляю пользователю как кнопку trinidad с fileDownloadActionListener.

Я могу загрузить PDF-файл, но не могу открыть его с помощью PDF reader, например, сначала с помощью Adobe Reader Я подумал, что он может быть поврежден, но это не так, потому что я могу открыть его с помощью Visual Studio Code или любой другой текстовый редактор, например notepad.

1- почему я не могу открыть его с помощью Adobe Reader?

2- Есть ли что-нибудь лучше, зачем это делать?

Фронтенд:

<h:commandButton id="mehrpdf" value="Download PDF" styleClass="popupButton">
        <tr:fileDownloadActionListener filename="mehr.pdf"  contentType="application/pdf; charset=utf-8" method="#{bean.downloadMehr}" />
</h:commandButton>

Бэкэнд:

public void downloadMehr(FacesContext context, OutputStream out) throws IOException
    {
        String fetchedXmlMessage = getFetchedXmlMessage();
        XmlPrettifier prettifier = XmlPrettifierFactory.getInstance();
        prettyXmlMessage = prettifier.makePretty(fetchedXmlMessage);

        // alternativ way
        File pdfFile = createPdfFromTxt(prettyXmlMessage);

        OutputStreamWriter w = new OutputStreamWriter(out, "UTF-8");
        w.write(prettyXmlMessage);
        w.flush();
    }

pdfcreation:

public File createPdfFromTxt(String content) throws IOException, DocumentException {

        //define the size of the PDF file, version and output file
        File outfile = File.createTempFile("mehr", ".pdf");
        Document pdfDoc = new Document(PageSize.A4);
        PdfWriter.getInstance(pdfDoc, new FileOutputStream(outfile)).setPdfVersion(PdfWriter.PDF_VERSION_1_7);
        pdfDoc.open();

        //define the font and also the command that is used to generate new paragraph
        Font myfont = new Font();
        myfont.setStyle(Font.NORMAL);
        myfont.setSize(11);
        pdfDoc.add(new Paragraph("\n"));

        // add paragraphs into newly created PDF file
        File contentFile = File.createTempFile("content", ".txt");
        FileUtils.writeStringToFile(contentFile, content);

        BufferedReader br = new BufferedReader(new FileReader(contentFile));
        String strLine;
        while ((strLine = br.readLine()) != null) {
            Paragraph para = new Paragraph(strLine + "\n", myfont);
            para.setAlignment(Element.ALIGN_JUSTIFIED);
            pdfDoc.add(para);
        }
        pdfDoc.close();
        br.close();

        return outfile;
    }

1 Ответ

2 голосов
/ 17 июня 2020

Я изменил серверную часть, как показано ниже, в соответствии с тем, что люди упомянули в приведенной выше команде, теперь я могу читать ее с помощью программы для чтения PDF. Спасибо всем вам.

public void downloadMehr(FacesContext context, OutputStream out) throws IOException
    {
        String fetchedXmlMessage = getFetchedXmlMessage();
        XmlPrettifier prettifier = XmlPrettifierFactory.getInstance();
        prettyXmlMessage = prettifier.makePretty(fetchedXmlMessage);

        // create pdf from string
        PdfCreator pdfCreator = new PdfCreator( prettyXmlMessage);
        File pdfFile = pdfCreator.create();

        FileInputStream inStream = new FileInputStream(pdfFile);
        byte[] buffer = new byte[4096];
        int bytesRead = -1;

        while ((bytesRead = inStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }

        inStream.close();
        outputStream.close();
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...