简体   繁体   中英

Convert byte array of docx format to byte array of pdf format directly

是否有任何可能的方法可以直接将 docx/txt 或任何格式的字节数组转换为 pdf 格式的字节数组,而无需创建 pdf 文件。

I believe, you can achieve this by using the following code of Aspose.Words for Java :

ByteArrayInputStream inStream = byte array of DOCX/TXT;
// Load Document from inStream
Document doc = new Document(inStream);

/* Perform any document processing tasks here */

// Save the modified document into out stream
ByteArrayOutputStream baos = new ByteArrayOutputStream();
doc.save(baos, SaveFormat.PDF);

// You can then get the PDF document back into the InputStream as follows
InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());

Please also check the file formats that you can currently convert to PDF (byte array or save to disk) using Aspose.Words for Java. I work with Aspose as Developer Evangelist.

I tried so much ways to do that with Apache Poi and faced so much troubles, because of moving POIXMLDocumentPart.class to another package in new version of Apache POI Xwpf Converter PDF. I spent aproximately 6 hours trying to do smth, then I finally found another convertion library - Documents4j . Recommend trying. Works great for me.

Pom:

<documents4j.version>1.1.7</documents4j.version>

<dependency>
    <groupId>com.documents4j</groupId>
    <artifactId>documents4j-local</artifactId>
    <version>${documents4j.version}</version>
</dependency>
<dependency>
    <groupId>com.documents4j</groupId>
    <artifactId>documents4j-transformer-msoffice-word</artifactId>
    <version>${documents4j.version}</version>
</dependency>

Java:

public class FileConvertionServiceImpl implements FileConvertionService {

    @Override
    public byte[] convert(byte[] input, DocumentType inputType, DocumentType outputType) {
        ByteArrayInputStream inputStream = new ByteArrayInputStream(input);
        ByteArrayOutputStream output = new ByteArrayOutputStream();

        LocalConverter.builder().build()
                .convert(inputStream).as(inputType)
                .to(output).as(outputType)
                .execute();

        closeOutputStream(output);
        return output.toByteArray();
    }

    private void closeOutputStream(ByteArrayOutputStream output) {
        try {
            output.close();
        } catch (IOException e) {
            log.error("Can't close OutputStream after file convertion: ", e);
            e.printStackTrace();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM