Page cover

PDF

1. Giới thiệu

Giả sử chúng ta muốn tải thông tin resume của một người về.

Như vậy chúng ta cần có file pdf để lưu thông tin của người đó.

Xét 2 trường hợp sau:

  • Người ta upload file pdf và việc chúng ta là lưu thông tin file lại ở một nơi nào đó, khi cần download thì chúng ta sẽ trả về file đó.

  • Một trường hợp chúng ta lưu thông tin của người đó dưới dạng database, khi cần chúng ta sẽ export ra file pdf để trả về.

Ở trong bài viết này hướng dẫn trường hợp thứ 2, export file pdf.

2. Tạo file pdf theo yêu cầu

Ý tưởng của việc giải quyết này là: chúng ta sẽ đọc thông tin từ request của user sau đó tạo ra file pdf theo yêu cầu của họ, và lưu vào public folder. Vì file lưu vào public folder nên người dùng sẽ có thể truy cập vào folder được.

Thư viện sử dụng là: pdfkit

// Some code
function createPdfFile(fileName, name) {
  const PDFDocument = require("pdfkit");
  const fs = require("fs");

  // Create a document
  const doc = new PDFDocument();

  // Pipe its output somewhere, like to a file or HTTP response
  // See below for browser usage
  doc.pipe(fs.createWriteStream(fileName));
  doc.fontSize(25).text("Xin chào " + name, 100, 100);
  // Embed a font, set the font size, and render some text
  //   doc
  //     .font("fonts/PalatinoBold.ttf")
  //     .fontSize(25)
  //     .text("Some text with an embedded font!", 100, 100);

  // Add an image, constrain it to a given size, and center it vertically and horizontally
  doc.image("./public/images/NewerCampFire.png", {
    fit: [250, 300],
    align: "center",
    valign: "center",
  });

  // Add another page
  doc.addPage().fontSize(25).text("Here is some vector graphics...", 100, 100);

  // Draw a triangle
  doc.save().moveTo(100, 150).lineTo(100, 250).lineTo(200, 250).fill("#FF3300");

  // Apply some transforms and render an SVG path with the 'even-odd' fill rule
  doc
    .scale(0.6)
    .translate(470, -380)
    .path("M 250,75 L 323,301 131,161 369,161 177,301 z")
    .fill("red", "even-odd")
    .restore();

  // Add some text with annotations
  doc
    .addPage()
    .fillColor("blue")
    .text("Here is a link!", 100, 100)
    .underline(100, 100, 160, 27, { color: "#0000FF" })
    .link(100, 100, 160, 27, "http://google.com/");

  // Finalize PDF file
  doc.end();
}

Và nên nhớ use public folder

// Some code
app.use(express.static(path.join(__dirname, "public")));
app.use("/public", express.static(path.join(__dirname, "public")));

app.use("/", indexRouter);
app.use("/users", usersRouter);
app.use("/api/pdf/h", (req, res) => {
  const fileName = "./public/output.pdf";
  console.log(req.query);
  createPdfFile(fileName, req.query.name);
  res.redirect("http://127.0.0.1:3000" + fileName.substring(1));
});

3. Sử dụng Stream pdf file

Last updated

Was this helpful?