- Published on
ทำ API ให้แสดงไฟล์ PDF บน Express
![ทำ API ให้แสดงไฟล์ PDF บน Express](https://assets.me-idea.in.th/blogs/create-an-api-to-display-pdf-files-with-express/create-an-api-to-display-pdf-files-with-express.webp)
อันยองฮาเซโยววว สวัสดีคุณผู้อ่านทุกท่านเน้อครับ วันนี้เจมส์จะมาเขียนเกี่ยวกับการทำ API ให้แสดงผลเป็น PDF (PDF อันนี้เราอาจจะเรียกจากไฟล์ หรือเรียกจากอีก API นึงก็ได้ครับ) พอดีเจมส์ได้ทำเรียกผ่าน API คือที่บริษัทมี Service ที่ Response ข้อมูลเป็น PDF ออกมา
คราวนี้เจมส์ต้องใช้ API ไปเรียกที่ Service นี้ เลยเป็นที่มาของบทความนี้ครับ ^^
มาเริ่มกันเลย
ขั้นแรกเดี๋ยวเราสร้าง Project ขึ้นมาก่อนเน้อครับ และก็เข้าไปที่โปรเจคนั้นครับ
mkdir express-display-pdf && cd express-display-pdf
จากนั้น init ไฟล์ package.json ขึ้นมา ด้วยคำสั่ง
npm init -y
จากนั้นให้ install express
และ axios
ครับ ด้วยคำสั่ง
npm install express axios --save
สร้างไฟล์ server.js
ขึ้นมาครับ แล้วใส่โค้ดลงไปดังนี้ครับ
const express = require("express");
const axios = require("axios");
const app = express();
const PORT = 2000;
app.get("/get-pdf", async (req, res) => {
try {
// Make a request to another service to get the PDF
const response = await axios({
method: "get",
url: "https://assets.me-idea.in.th/blogs/create-an-api-to-display-pdf-files-with-express/example.pdf",
responseType: "stream", // This is important for handling binary data (e.g., PDF)
});
// Set the appropriate headers for a PDF response
res.setHeader("Content-Type", "application/pdf");
res.setHeader("Content-Disposition", 'inline; filename="example-file.pdf"');
// Pipe the response directly to the client
response.data.pipe(res);
} catch (error) {
console.error("Error fetching PDF:", error.message);
res.status(500).send("Internal Server Error");
}
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
จากนั้นให้ start server ด้วยคำสั่ง
node server.js
แล้วลองเข้า http://localhost:2000/get-pdf จะพบว่ามี PDF แสดงเรียบร้อยแล้ว ซึ่ง PDF ที่แสดงถูกดึงมาจาก https://assets.me-idea.in.th/blogs/create-an-api-to-display-pdf-files-with-express/example.pdf
ถ้าอยากให้เมื่อเข้าแล้วเป็น Download PDF แทนการแสดง PDF เราจะเปลี่ยนในส่วน
Content-Disposition
โดยจะเปลียนinline
เป็นattachment
แทน
res.setHeader("Content-Disposition", 'attachment; filename="example-file.pdf"');
ซึ่งถ้าเป็น attachment
เมื่อเข้าลิงค์เดิม จากตอนแรกแสดงเป็น PDF
ในตอนนี้จะเป็น Download PDF แทน
หากคุณผู้อ่านเปลี่ยนแล้วยังแสดงเป็นหน้า PDF อยู่ ให้สั่ง start server ใหม่อีกครั้งครับ
หวังว่าบทความนี้จะมีประโยชน์กับคุณผู้อ่านเน้อครับ หากบทความนี้มีส่วนไหนผิดพลาดประการใด ก็ขออภัยมา ณ ที่นี้ด้วยเน้อครับ หรือหากคุณผู้อ่านมีข้อสงสัยในส่วนไหน สามารถพิมพ์คำถามทิ้งไว้ในคอมเม้นท์ด้านล่างได้เลยครับ ^^
Happy Coding!