Как получить PDF в байтах [] без формирования файла? - PullRequest
0 голосов
/ 25 октября 2018

Ниже приведен мой фрагмент кода:

 try (OutputStream out = new FileOutputStream(PDF_NAME)) {
            Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = factory.newTransformer(new StreamSource(xsltFile));
            Result res = new SAXResult(fop.getDefaultHandler());
            transformer.transform(new StreamSource(IOUtils.toInputStream(xml, "UTF-8")), res);
        }
    byte[] inputFile = Files.readAllBytes(Paths.get(PDF_NAME));
    String encodedFile = Base64.getEncoder().encodeToString(inputFile);
    InventoryListSnapshot pojo = new InventoryListSnapshot(invList.getInventoryLayoutId(), invList.getProjectId(), invList.getAuthorUsername(), encodedFile);
    repository.save(pojo);

Он использовал xsl-fo для формирования PDF в файле.Мне нужно поместить этот PDF-файл, закодированный Base64 как BLOB, в БД - поэтому я не использую сам файл.

Как сохранить PDF в БД без формирования файла?

Ответы [ 2 ]

0 голосов
/ 25 октября 2018

Спасибо, все работает.Новая версия:

byte[] pdf;
    try (OutputStream out = new ByteArrayOutputStream()){
        Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer(new StreamSource(xsltFile));
        Result res = new SAXResult(fop.getDefaultHandler());
        transformer.transform(new StreamSource(IOUtils.toInputStream(xml, "UTF-8")), res);
        pdf = ((ByteArrayOutputStream) out).toByteArray();
    }
    String encodedFile = Base64.getEncoder().encodeToString(pdf);
    InventoryListSnapshot pojo = new InventoryListSnapshot(invList.getInventoryLayoutId(), invList.getProjectId(), invList.getAuthorUsername(), encodedFile);
    repository.save(pojo);
0 голосов
/ 25 октября 2018

Вы бы изменили это:

OutputStream out = new FileOutputStream(PDF_NAME)

на

OutputStream out = new ByteArrayOutputStream()
...