首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在Java中将InputStream转换为PDF,而不损坏文件?

在Java中,将InputStream转换为PDF文件通常意味着您正在尝试将某种数据流(可能是来自网络、文件系统或其他来源的数据)保存为PDF格式

以下是一个简单的示例,说明如何使用iText库将InputStream的内容保存为PDF文件:

代码语言:javascript
复制
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class InputStreamToPDF {

    public static void main(String[] args) {
        InputStream inputStream = ...; // 获取您的InputStream
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream("output.pdf");

            Document document = new Document();
            PdfWriter.getInstance(document, outputStream);
            document.open();

            // 假设InputStream包含纯文本
            byte[] buffer = new byte[1024];
            int bytesRead;
            StringBuilder sb = new StringBuilder();
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                sb.append(new String(buffer, 0, bytesRead));
            }
            document.add(new Paragraph(sb.toString()));

            document.close();
        } catch (DocumentException | IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

注意:

  1. 这个示例假设InputStream包含纯文本,并将其添加到PDF中。如果您的InputStream包含二进制数据(例如图像),则需要使用适当的方法来处理这些数据。
  2. 这个示例使用了iText库,这是一个功能强大的PDF库,但请注意,它不是免费的。如果您正在寻找开源替代方案,可以考虑使用Apache PDFBox。
  3. 在处理文件和流时,请始终确保正确关闭它们,以避免资源泄漏。
页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

  • SpringBoot 下PDF生成使用填坑总结

    解释: 1、Configuration cfg 使用了freemaker starter后,在项目启动时即会自动初始化 Configuration 对象到Spring容器中; 2、Template template = cfg.getTemplate("test.ftl","UTF-8"); 模板因cfg本身在Spring容器中,则在获取test.ftl模板是就会自动在resource/templates下寻找模板,默认:ftl 格式,可以修改 3、因为找了很多例子都是使用ITextRenderer 对象来渲染输出渲染的PDF,但ITextRenderer有一个问题是要解决中文不显示问题,必须把字体放在一个以 文件夹 路径访问的形式引入,SpringBoot打包后,经测试,无法获取打包后的FONT字体; 则,再另辟途径,又找到以Document方式,但document需要的是,没一个dom对象都必须一个个添加进去,网上很多都是new 专门的对象,比如:块 Paragraph 然后添加文字(数字)内容。 所以又搜索:是否可以往document插入html 最终找到:https://www.cnblogs.com/mvilplss/p/5646675.html

    03

    Java实现在线预览–openOffice实现[通俗易懂]

    #Java实现在线预览–openOffice实现 ##简介 之前有写了poi实现在线预览的文章,里面也说到了使用openOffice也可以做到,这里就详细介绍一下。 我的实现逻辑有两种: 一、利用jodconverter(基于OpenOffice服务)将文件(.doc、.docx、.xls、.ppt)转化为html格式。 二、利用jodconverter(基于OpenOffice服务)将文件(.doc、.docx、.xls、.ppt)转化为pdf格式。 转换成html格式大家都能理解,这样就可以直接在浏览器上查看了,也就实现了在线预览的功能;转换成pdf格式这点,需要用户安装了Adobe Reader XI,这样你会发现把pdf直接拖到浏览器页面可以直接打开预览,这样也就实现了在线预览的功能。 ##将文件转化为html格式或者pdf格式 话不多说,直接上代码。

    03

    java实现在线预览–poi实现word、excel、ppt转html

    ###简介 java实现在线预览功能是一个大家在工作中也许会遇到的需求,如果公司有钱,直接使用付费的第三方软件或者云在线预览服务就可以了,例如永中office、office web 365(http://www.officeweb365.com/)他们都有云在线预览服务,就是要钱0.0 如果想要免费的,可以用openoffice,还需要借助其他的工具(例如swfTools、FlexPaper等)才行,可参考这篇文章http://blog.csdn.net/z69183787/article/details/17468039,写的挺细的,实现原理就是: 1.通过第三方工具openoffice,将word、excel、ppt、txt等文件转换为pdf文件; 2.通过swfTools将pdf文件转换成swf格式的文件; 3.通过FlexPaper文档组件在页面上进行展示。 当然如果装了Adobe Reader XI,那把pdf直接拖到浏览器页面就可以直接打开预览,这样就不需要步骤2、3了,前提就是客户装了Adobe Reader XI这个pdf阅读器。 我这里介绍通过poi实现word、excel、ppt转html,这样就可以放在页面上了。

    02

    word转出图片(使用免费插件)02

    /**      * 将word文档, 转换成pdf, 中间替换掉变量      * @param source 源为word文档, 必须为docx文档      * @param target 目标输出      * @param params 需要替换的变量      * @throws Exception      */     public static void wordConverterToPdf(InputStream source,                                           OutputStream target, Map<String, String> params) throws Exception {         wordConverterToPdf(source, target, null, params);     }     /**      * 将word文档, 转换成pdf, 中间替换掉变量      * @param source 源为word文档, 必须为docx文档      * @param target 目标输出      * @param params 需要替换的变量      * @param options PdfOptions.create().fontEncoding( "windows-1250" ) 或者其他      * @throws Exception      */     public static void wordConverterToPdf(InputStream source, OutputStream target,                                           PdfOptions options,                                           Map<String, String> params) throws Exception {         //HWPFDocument doc=new HWPFDocument(source);         XWPFDocument doc = new XWPFDocument(source);         paragraphReplace(doc.getParagraphs(), params);         for (XWPFTable table : doc.getTables()) {             for (XWPFTableRow row : table.getRows()) {                 for (XWPFTableCell cell : row.getTableCells()) {                     paragraphReplace(cell.getParagraphs(), params);                 }             }         }         PdfConverter.getInstance().convert(doc, target, options);     }     /** 替换段落中内容 */     private static void paragraphReplace(List<XWPFParagraph> paragraphs, Map<String, String> params) {         if (MapUtils.isNotEmpty(params)) {             for (XWPFParagraph p : paragraphs){                 for (XWPFRun r : p.getRuns()){                     String content = r.getText(r.getTextPosition());                     if(StringUtils.isNotEmpty(content) && params.containsKey(content)) {                         r.setText(params.get(content), 0);                     }                 }             }         }     }

    01
    领券