用pdfbox创建文件并下载[solved]

czq61nw1  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(581)

我在这里看到了很多答案,我复制了一些例子,并尝试应用它,但我不知道如何使这个工作。我正在尝试用pdfbox创建一个文件并发送一个响应,这样用户就可以下载它了。到目前为止,我可以下载文件,但它是空白的。我已经试过用pdfbox从我的电脑上加载一个示例文件并下载它,但结果是一样的,空白。我现在使用的代码是:

@GET
@Path("/dataPDF")
@Produces("application/pdf") 
public Response retrievePDF(){

        try {
                ByteArrayOutputStream output = new ByteArrayOutputStream();

                output = createPDF();
                ResponseBuilder response = Response.ok(output.toByteArray(), "application/pdf");
                response.header("Content-Disposition","attachment; filename=file.pdf");
                return response.build();
        } 
        catch (Exception ex) {                    
                ex.printStackTrace();
                return Response.status(Response.Status.NOT_FOUND).build();
        }
public ByteArrayOutputStream createPDF() throws IOException {    

        PDFont font = PDType1Font.HELVETICA;
        PDPageContentStream contentStream;
        ByteArrayOutputStream output =new ByteArrayOutputStream();   
        PDDocument document =new PDDocument(); 
        PDPage page = new PDPage();
        document.addPage(page);
        contentStream = new PDPageContentStream(document, page);           
        contentStream.beginText();        
        contentStream.setFont(font, 20);        
        contentStream.newLineAtOffset(10, 770);        
        contentStream.showText("Amount: $1.00");        
        contentStream.endText();

        contentStream.beginText();        
        contentStream.setFont(font, 20);        
        contentStream.newLineAtOffset(200, 880);               
        contentStream.showText("Sequence Number: 123456789");        
        contentStream.endText();        

        contentStream.close(); 

        document.save(output);    
        document.close();    
        return output; 
      }

更新1:所以文件正在创建中,现在我在将它发送到web时遇到了问题,我使用的是reactjs。我试着调整我用来下载csv文件的结构,如下所示:

const handleExportPDF= fileName => {
        FileController.retrievePDF().then((response) => {
            const url = window.URL.createObjectURL(new Blob([response.data]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', fileName);
            document.body.appendChild(link);
            link.click();
          });

    };
static retrievePDF() {
        const { method, url } = endpoints.retrievePDF();
        return api[method](url,{
            responseType: "application/pdf"
        });
    }
export const fileEndpoints = {
    retrievePDF: () => ({
        method: "get",
        url: `/export/dataPDF`
    })
};

更新2:如果有人在这里绊倒了,我可以在这里解决这个问题的答案:pdf blob-弹出窗口不显示内容。这一点正在改变 responseType: "application/pdf"responseType: 'arraybuffer' 即使改变这个已经奏效了,我也改变了 window.URL.createObjectURL(new Blob([response.data]));window.URL.createObjectURL(new Blob([response.data]), {type: 'application/pdf'});

knpiaxh1

knpiaxh11#

使用下面的测试代码,您可以验证生成pdf的源代码是否正常工作。
但是第二个textelement的位置不在视口中。
看起来您的问题与webframework有关。你可以提供更多的细节,以供进一步的建议。
pom.xml文件

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.mycompany.app</groupId>
<artifactId>my-app</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
    <maven.compiler.source>11</maven.compiler.source>
    <maven.compiler.target>11</maven.compiler.target>
</properties>

<dependencies>
    <dependency>
        <groupId>org.apache.pdfbox</groupId>
        <artifactId>pdfbox</artifactId>
        <version>2.0.19</version>
    </dependency>
</dependencies>

应用程序.java

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;

import java.io.*;

public class App {

    public static void main(String[] args) throws  IOException {
        File resultFile = File.createTempFile("Test",".pdf");
        ByteArrayOutputStream byteArrayOutputStream = createPDF();
        try(OutputStream outputStream = new FileOutputStream(resultFile)) {
            byteArrayOutputStream.writeTo(outputStream);
        }
        System.out.println("Please find your PDF File here: " + resultFile.getAbsolutePath());
    }

    public static ByteArrayOutputStream createPDF() throws IOException {
        PDFont font = PDType1Font.HELVETICA;
        PDPageContentStream contentStream;
        ByteArrayOutputStream output =new ByteArrayOutputStream();
        PDDocument document =new PDDocument();
        PDPage page = new PDPage();
        document.addPage(page);
        contentStream = new PDPageContentStream(document, page);
        contentStream.beginText();
        contentStream.setFont(font, 20);
        contentStream.newLineAtOffset(10, 770);
        contentStream.showText("Amount: $1.00");
        contentStream.endText();

        contentStream.beginText();
        contentStream.setFont(font, 20);
        // 200 is way too much right and 800 too much on top... so this want be visible on normal A4 Format
        contentStream.newLineAtOffset(200, 880);
        contentStream.showText("Sequence Number: 123456789");
        contentStream.endText();

        contentStream.close();

        document.save(output);
        document.close();
        return output;
    }

}

相关问题