Я создаю 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;
}