代码之家  ›  专栏  ›  技术社区  ›  Glyn

如何将pdf生成为变量而不是文件?

  •  0
  • Glyn  · 技术社区  · 5 年前

    我正在创建一个pdf文件并将其存储在一个目录中。我现在想传回pdf数据,这样用户就可以下载到他们喜欢的目录(即,不再在目录中创建文件)。我如何创建“pdfData”来传回?

    我知道这需要用变量的名称替换“new FileOutputStream(FILE)”,以存储数据;但是,我无法解决这个问题,也无法在网上找到一个示例。

    String filePath = System.getProperty("user.home") + "\\Documents\\"+fileName; //Test use
    Document document = new Document(PageSize.A4, 72f, 72f, 72f, 72f);
    try {
        PdfWriter.getInstance(document, new FileOutputStream(FILE));
        document.open();
        addMetaData(document);
        addImages(document);
        addTitlePage(document, recipeDetails, recipeName, servings, servingSize);
        document.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
    //return pdfData;
    
    0 回复  |  直到 5 年前
        1
  •  1
  •   Paul Jowett    5 年前

    要显示mkl建议与代码合并的内容:

    String filePath = System.getProperty("user.home") + "\\Documents\\"+fileName; //Test use
    Document document = new Document(PageSize.A4, 72f, 72f, 72f, 72f);
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter.getInstance(document, baos);
        document.open();
        addMetaData(document);
        addImages(document);
        addTitlePage(document, recipeDetails, recipeName, servings, servingSize);
        document.close();
    
        byte[] pdfData = baos.toByteArray();
        return pdfData;
    
    } catch (Exception e) {
      e.printStackTrace();
    }
    

    pdfData是一个byte[](字节数组)。这可以作为实际的pdf文件直接流式传输/存储到任何地方。请记住,这是将PDF写入内存,因此如果同时执行大量大型PDF,则会出现可伸缩性问题。

    我希望这有帮助。

    推荐文章