0

I generate a pdf with with express and pdfkit like:

router.get("/create_pdf", (req, res) => {
  var foo = req.body.foo;
  var bar = req.body.bar;

  // query Postgres with foo and bar to get some custom values
  
  //create pdf
  const doc = new PDFDocument();
  doc.pipe(res);
  doc.fontSize(25).text("Just a header", 100, 80);

  // build some more stuff depending of Postgres query

  doc.end();
})

My frontend using vue receives the response

print: function() {
  data = {foo: "foo", bar: "bar"};

  this.axios({
    method: "get",
    url: "get_recipe_as_pdf",
    data: data,
  })
    .then((response) => {
      console.log(response);
      window.open(response.data);
    })
    .catch(() => {
      //some error
    });
},

The console shows data: "%PDF-1.3↵%����↵7 0 obj↵<...

window.open(...) opens a blank tab.

I found similar questions but could not find an answer. I probably have some understanding problems, so I'd appreciate a hint. Thanks.

Oleksii Zelenko
  • 2,311
  • 3
  • 7
  • 21
AndreasInfo
  • 1,062
  • 11
  • 26

1 Answers1

0

In your express app: res.setHeader('Content-Type', 'application/pdf');

In your frontend just open the link "manually" like clicking on an anchor: <a href="{url to pdf}" target="_blank">click me</a>

The pdf should open in a new tab if your browser supports that, else it will be downloaded.

Edit: for clarification: window.open expects a url as first parameter, not the content of a pdf.

bouffelec
  • 174
  • 1
  • 9
  • Thanks for the answer. Do I understand right, that I have to save the pdf somewhere? My plan was to create it some on-the-fly. And this approach does not work, if I want to send some data via ajax as well. Sorry if the question was not specific enough. I updated the question. – AndreasInfo Feb 12 '21 at 12:18
  • You do not need to save it on the server side. You can pipe it into the res directly. – bouffelec Feb 12 '21 at 14:40
  • Maybe look at the pdfkit documentation again. If this question (https://stackoverflow.com/questions/58090447/expressjs-and-pdfkit-generate-a-pdf-in-memory-and-send-to-client-for-download) is correct, than you are missing something on your server side. You client side code definitely won't work, you cannot provide a pdf blob to the window.open method. – bouffelec Feb 12 '21 at 14:42