簡體   English   中英

從pdfKit生成的緩沖區制作blob url

[英]make blob url from buffer generated by pdfKit

我在我的快速服務器中使用 pdfKit 生成帶有圖像的 pdf(每頁一個圖像),我將 pdfKit 生成的緩沖區發送到前端以便可以下載,這是我的 /genpdf 路由的處理程序:

res.setHeader('Content-Disposition', 'attachment; filename=mypdf.pdf');
res.setHeader('Content-Type', 'application/octet stream');
res.status(200).send(pdfBuffer) // this is the buffer generated by pdfKit

如果我直接在導航器上訪問該路線(/genpdf),它工作得很好,它會在新選項卡中打開 pdf(帶有圖像,每頁一個)。

但是,當我想在我的 react 應用程序中使用該 pdf 緩沖區創建可下載的 url 時,問題就來了。

const res = await axios.get('/genpdf'); 
const url = window.URL.createObjectURL(new Blob([res.data]));

這會生成一個 url,當我訪問該 url 時,它會打開一個帶有 pdf 的新選項卡,但所有頁面都是空白的,所以假設我生成了一個包含 5 個圖像的 pdf,它會打開一個包含 5 個頁面的 pdf,但它們都是空白的。

編輯:

我沒有意識到的一個細節是,如果我打開帶有空白頁的 pdf 打開的選項卡的控制台,我可以看到來自pdf.worker.js的這些消息

Warning: Invalid absolute docBaseUrl: "blob:http://localhost:3000/3b38c310-f7a6-4950-b16b-e92369ddc810".
Warning: Indexing all PDF objects
Warning: Invalid stream: "FormatError: Bad FCHECK in flate stream: 120, 239"
Warning: Invalid stream: "FormatError: Bad FCHECK in flate stream: 120, 239"
Warning: Invalid stream: "FormatError: Bad FCHECK in flate stream: 120, 239"

這個來自viewer.js

PDF 538c033f41b7213bc8cc8e2c7c937518 [1.3 PDFKit / PDFKit] (PDF.js: 2.14.290)

這個來自pdf.js

mozCurrentTransform is deprecated and will be removed in the future. Use CanvasRenderingContext2D.getTransform() or CanvasRenderingContext2D.setTransform() instead.

我在這里缺少什么?

所以假設我們發送給客戶端的是一個緩沖區(不是數組緩沖區)並且我們使用的是 axios,我們這樣處理它:

const requestDocument = async () => {
  const response = await axios.get('/getdocument', {
    responseType: 'blob',
    headers: {
      'Content-Type': 'application/pdf'
    }
  })
  const blob = new Blob([response.data], { type: 'application/pdf' });
  const url = window.URL.createObjectURL(blob);
}

發送緩沖區時,我不必設置特殊的標頭,正如我在問題中提到的,我發送給客戶端的緩沖區是 pdfKit 生成的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM