如何在不将文件存储在服务器端的情况下向浏览器提供 PDF?

2024-01-04

我有两个方法。一种在服务器端生成 PDF,另一种在客户端下载 PDF。

我怎样才能做到这一点而不将其存储在服务器端并允许客户端直接下载它。

以下是两种方法:

public void downloadPDF(HttpServletRequest request, HttpServletResponse response) throws IOException{

    response.setContentType("application/pdf");
    response.setHeader("Content-disposition","attachment;filename="+ "testPDF.pdf");
    FileInputStream fis = null;
    DataOutputStream os = null;

    try {
        File f = new File("C://New folder//itext3.pdf");
        response.setHeader("Content-Length",String.valueOf(f.length()));

        fis = new FileInputStream(f);
        os = new DataOutputStream(response.getOutputStream());
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = fis.read(buffer)) >= 0) {
            os.write(buffer, 0, len);
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        fis.close();
        os.flush();
        os.close();
    }
    response.setHeader("X-Frame-Options", "SAMEORIGIN");
}

And:

public Document generatePDF() {

    Document doc = new Document();
     try {
            File file = new File("C://New folder//itext_Test2.pdf");
            FileOutputStream pdfFileout = new FileOutputStream(file);
            PdfWriter.getInstance(doc, pdfFileout);

            doc.addAuthor("TestABC");
            doc.addTitle("Aircraft Details");
            doc.open();


            Anchor anchor = new Anchor("Aircraft Report");
            anchor.setName("Aircraft Report");

            Chapter catPart = new Chapter(new Paragraph(anchor), 1);

            Paragraph para1 = new Paragraph();
            Section subCatPart = catPart.addSection(para1);
            para1.add("This is paragraph 1");

            Paragraph para2 = new Paragraph();
            para2.add("This is paragraph 2");


            doc.add(catPart);

            doc.close();


        } catch (Exception e) {
            e.printStackTrace();
        }
     return doc;
}

建议您使用的人response.getOutputStream()而不是创建一个FileOutputStream是对的。例如参见Hello http://itextpdf.com/examples/iia.php?id=167我的书第 9 章中的 Servlet:

public class Hello extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        response.setContentType("application/pdf");
        try {
            // step 1
            Document document = new Document();
            // step 2
            PdfWriter.getInstance(document, response.getOutputStream());
            // step 3
            document.open();
            // step 4
            document.add(new Paragraph("Hello World"));
            document.add(new Paragraph(new Date().toString()));
            // step 5
            document.close();
        } catch (DocumentException de) {
            throw new IOException(de.getMessage());
        }
    }
}

但是,当您像这样直接发送字节时,某些浏览器会遇到问题。使用以下方式在内存中创建文件更安全ByteArrayOutputStream并告诉浏览器在内容标头中可以期望有多少字节:

public class PdfServlet extends HttpServlet {

    protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        try {
            // Get the text that will be added to the PDF
            String text = request.getParameter("text");
            if (text == null || text.trim().length() == 0) {
                 text = "You didn't enter any text.";
            }
            // step 1
            Document document = new Document();
            // step 2
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PdfWriter.getInstance(document, baos);
            // step 3
            document.open();
            // step 4
            document.add(new Paragraph(String.format(
                "You have submitted the following text using the %s method:",
                request.getMethod())));
            document.add(new Paragraph(text));
            // step 5
            document.close();

            // setting some response headers
            response.setHeader("Expires", "0");
            response.setHeader("Cache-Control",
                "must-revalidate, post-check=0, pre-check=0");
            response.setHeader("Pragma", "public");
            // setting the content type
            response.setContentType("application/pdf");
            // the contentlength
            response.setContentLength(baos.size());
            // write ByteArrayOutputStream to the ServletOutputStream
            OutputStream os = response.getOutputStream();
            baos.writeTo(os);
            os.flush();
            os.close();
        }
        catch(DocumentException e) {
            throw new IOException(e.getMessage());
        }
    }
}

完整源代码请参见PDFServlet http://developers.itextpdf.com/examples/itext-action-second-edition/chapter-9#377-pdfservlet.java。您可以尝试这里的代码:http://demo.itextsupport.com/book/ http://demo.itextsupport.com/book/

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在不将文件存储在服务器端的情况下向浏览器提供 PDF? 的相关文章

随机推荐

  • 如何为使用 jQuery Mobile、PhoneGap 和 Django 实现的移动 Web 应用程序实现仅首次登录方案?

    我正处于开发移动 Web 应用程序的早期 预编码 阶段jQuery 移动 http en wikipedia org wiki JQuery Mobile 我们看了煎茶触摸 http en wikipedia org wiki Sencha
  • 发布查询,包括元数据和大于日期

    我正在努力寻找可行的解决方案wp query 我目前有一些分配给帖子的自定义设置 一是帖子是否 精选 二是帖子结束的日期和时间 不再显示在结果中 我有使用该功能的查询 但只需要将此结束日期纳入其中 这是使用 特色 查找的查询 WP Quer
  • 向 C++ 控制台应用程序添加状态栏

    我正在使用 C 制作一个 Linux 应用程序 它会将信息打印到控制台 程序的某些部分将需要一段时间来计算 我想在控制台中添加一个类似于 wget 中使用的状态栏 我在下面放置了我自己的描述 complete gt eta 实现这一目标的最
  • 绑定参数 4 时出错 - 可能是不受支持的类型

    我首先要提到的是 我通过 Flask SqlAlchemy 使用 SqlAlchemy 我不认为这会影响该问题 但如果会影响 请告诉我 这是我在 SqlAlchemy 中运行 create all 函数时收到的错误消息的相关部分 Inter
  • Android - 丢失传入(高速)USB 数据

    使用 Android 时 我会丢失传入 USB 数据流上的数据 而在 Windows 中读取同一设备 流时不会丢失这些数据 我知道 Android 不是实时操作系统 但 Windows 也不是 并且 Windows 在 跟上 数据方面没有任
  • 使用正则表达式检查字符串是否只包含一位数字

    我正在编写一个算法 我需要检查字符串是否包含only one数字 不超过一位 目前我有 if current Operation matches d 有更好的方法来做这件事吗 谢谢 您可以使用 D d D match beginning o
  • 如何将数据从托管程序集流式传输到本机库并再次返回?

    如何将数据 文本 从托管程序集流式传输到本机库并将数据 文本 流回托管程序集 具体来说 我想揭露一个System IO Stream NET 端的某种类型 并且 最重要的是 a FILE 在本机方面 本机方法的签名应该是 FILE foo
  • DataTable 上的 Linq:选择特定列到数据表中,而不是整个表

    我正在运行 LINQ 查询datatable in c 我想选择特定列而不是整行并将结果输入到datatable 我怎样才能做到这一点 My Code public DataTable getConversions string c to
  • 如何更新猫鼬中嵌入文档中的嵌入文档?

    我正在使用 mongodb 和 mongoose 在 node js 中构建一个 API 目前 我有一个嵌入文档中的嵌入文档 架构中的架构 它根本没有保存到数据库中 我已尽我所能 但没有运气 我在猫鼬中将架构定义为 var BlogPost
  • Volley AppController 类对象返回 null

    我正在制作一个应用程序JsonObjectRequest并使用 Android 版 Volley Networking Library 从 URL 检索 JSON 数据 应用控制器 java public class AppControll
  • 在 Visual Studio Code for Mac 中设置 TFVC 存储库

    我正在尝试在我的 Visual Studio Code for Mac 上的 VSTS 中设置托管的 Team Foundation 版本控制 TFVC 存储库 我根本没用过Visual Studio 显然 我的客户正在使用 TFVC 系统
  • Array.Clone() (复制还是不复制?)

    我怀疑我只是误解了 Array 类的 Clone 方法 然而它显示 创建 System Array 的浅拷贝 所以我认为这意味着新的对象指针 而不是相同的对象指针 下面的事情真的应该发生吗 假设测试对象 public class testO
  • 使用主机路径与 Kind Kubernetes Cluster 共享本地目录

    我想与 kind 集群共享我的非空本地目录 基于这里的答案 如何在 Kind 中引用本地卷 docker 中的 kubernetes https stackoverflow com questions 62694361 how to ref
  • Nginx / PHP FPM 优雅停止(SIGQUIT):不太优雅

    运行 nginx 1 9 PHP 7 0 但 5 6 中的行为也完全相同 尝试优雅地停止 PHP FPM nginx 组合以在维护期间关闭节点 为此 我将 SIGQUIT 发送到 php fpm 这should提供优雅的关闭 为了测试这一点
  • Android SearchView 样式下拉弹出窗口

    我想知道如何设计Android 4 0的下拉弹出窗口的样式SearchView 我正在使用Theme Sherlock Light DarkActionBar 但我不知道如何将下拉搜索样式设置为白色背景和黑色文本 由于某种原因 使用 sea
  • 多行字符串中的 YAML 注释

    YAML 是否支持多行字符串中的注释 我正在尝试做这样的事情 但验证器抛出错误 key comment value comment value value comments here don t work either 不 根据YAML 1
  • 在 CakePHP 中使用 HighchartsPHP 库

    我正在尝试使用ghunti的HighchartsPHP http www goncaloqueiros net highcharts phpCakePHP 中的包装器 以便我可以在我的项目中使用它 在演示中它说要编辑config php并包
  • Java 输入流到 Python (PY4J)

    我正在使用 PY4J 在 python 中运行 Java 代码 http py4j sourceforge net http py4j sourceforge net 我的java函数返回一个InputStream 我想在我的python代
  • 从 CDN 延迟加载

    是否可以从外部服务器加载惰性模块 我想将我的资源上传到 CDN 但似乎惰性模块是从我的 node js 服务器加载的 这对我来说并不好 我的服务器仅提供角度应用程序的index html 但资源将从cdn加载 它启动并正常工作 直到加载一个
  • 如何在不将文件存储在服务器端的情况下向浏览器提供 PDF?

    我有两个方法 一种在服务器端生成 PDF 另一种在客户端下载 PDF 我怎样才能做到这一点而不将其存储在服务器端并允许客户端直接下载它 以下是两种方法 public void downloadPDF HttpServletRequest r