Google Script से HTML को PDF में कन्वर्ट करने का आसान तरीका सिखाऊंगा

हेलो दोस्तों आज मैं आपको Google Script से HTML को PDF में कन्वर्ट करने का आसान तरीका सिखाऊंगा। तो चलिए आज के कोड स्निपेट के साथ शुरुआत करते हैं। अलग-अलग समस्याओं को प्राप्त करना पूरी तरह से एक बहुत ही अलग अनुभव देता है। आज मैं आपके साथ जो कोड स्निपेट साझा करने जा रहा हूं, वह Google स्क्रिप्ट के साथ HTML को PDF में बदलने का आसान तरीका है।

Google Script से HTML को PDF में कन्वर्ट करने का आसान तरीका सिखाऊंगा

Google Apps Script के साथ, आप आसानी से किसी भी HTML सामग्री को PDF फ़ाइल में बदल सकते हैं। परिवर्तित पीडीएफ फाइल को या तो आपके Google ड्राइव में एक फ़ोल्डर में सहेजा जा सकता है, आप फ़ाइल को अनुलग्नक के रूप में ईमेल कर सकते हैं या पीडीएफ फाइल को अमेज़ॅन एस 3 या ड्रॉपबॉक्स जैसी बाहरी सेवा में पोस्ट करने के लिए ऐप्स स्क्रिप्ट की UrlFetchApp सेवा का उपयोग कर सकते हैं।

आपको हमारे ट्रेंडिंग कोड स्निपेट भी पसंद आ सकते हैं

/* This function will convert HTML content to a PDF file, 
   and also send it as an email attachment */

const convertHTMLtoPDF = () => {
  const htmlContent = `
   <p>All standard HTML5 tags are supported during conversion
   including <b>bold</b>, <i>italic</i>, <u>underline</u>, tables,
   and <a href='https://digitalinspiration.com/'>inline URLs</a></p>`;

  const blob = Utilities.newBlob(htmlContent, MimeType.HTML);
  blob.setName("file.pdf");

  const recipientEmail = "amit@labnol.org";
  const emailSubject = "The PDF file is attached";

  MailApp.sendEmail({
    to: recipientEmail,
    subject: emailSubject,
    htmlBody: htmlContent,
    attachments: [blob.getAs(MimeType.PDF)],
  });
};

This approach is recommended since it doesn’t require access to any sensitive OAuth scopes and uses the Utilities services of Apps Script to create a Blob object from an HTML string.

Create PDF files with Google Drive

आप मध्यवर्ती चरण में Google दस्तावेज़ का उपयोग करके HTML सामग्री को PDF में कनवर्ट करने के लिए ऐप्स स्क्रिप्ट की उन्नत ड्राइव सेवा का भी उपयोग कर सकते हैं।

विचार यह है कि आप अपनी HTML सामग्री के साथ ड्राइव में एक Google दस्तावेज़ बनाते हैं और फिर उस दस्तावेज़ को PDF फ़ाइल के रूप में निर्यात करते हैं और अस्थायी दस्तावेज़ को मिटा देते हैं। या आप पीडीएफ ब्लॉब के साथ HTML दस्तावेज़ की सामग्री को ओवरराइड कर सकते हैं।

आरंभ करने के लिए, अपने ऐप्स स्क्रिप्ट संपादक पर जाएं, appsscript.json मेनिफेस्ट फ़ाइल खोलें और स्कोप अपडेट करें जैसा कि नीचे दिखाया गया है:

{
  "dependencies": {
    "enabledAdvancedServices": [
      {
        "userSymbol": "Drive",
        "serviceId": "drive",
        "version": "v2"
      }
    ]
  },
  "oauthScopes": ["https://www.googleapis.com/auth/drive.file"],
  "runtimeVersion": "V8",
  "timeZone": "Asia/Kolkata",
  "exceptionLogging": "STACKDRIVER"
}

Next, inside the main code editor, paste the following snippet. It takes a three step approach:

  1. Convert the HTML string to a blob
  2. Convert the Blob into a Google Document
  3. Export the Google Document as a PDF file and trash the file created in step 2.
const convertHTMLtoPDF = () => {
  const htmlContent = `
   <p>All standard HTML5 tags are supported during conversion
   including <b>bold</b>, <i>italic</i>, <u>underline</u>, tables,
   and <a href="https://digitalinspiration.com/">inline URLs</a></p>`;

  const { id, exportLinks } = Drive.Files.insert(
    { mimeType: MimeType.GOOGLE_DOCS },
    htmlBlob: Utilities.newBlob(htmlContent, MimeType.HTML)
  );

  const pdfExportLink = exportLinks[MimeType.PDF];

  const blob = UrlFetchApp.fetch(pdfExportLink, {
    headers: { Authorization: `Bearer ${ScriptApp.getOAuthToken()}` },
  }).getBlob();

  Drive.Files.trash(id);

  const { alternateLink } = Drive.Files.insert({ title: "file.pdf" }, blob);

  Logger.log("View file %s", alternateLink);
};

Tip: We are using the drive.file reduced scope in the manifest file but if you wish to save files in specific folders of your Google Drive, or Shared Team Drives, use the broader googleapis.com/auth/drive scope.

Convert HTML to PDF with Chrome Puppeteer

यदि आप एक स्टैंडअलोन HTML से PDF रूपांतरण इंजन बनाना चाहते हैं जो Google ड्राइव सेवाओं में से किसी का उपयोग नहीं करता है, तो Node JS के साथ Chrome Puppeteer एक अच्छा विकल्प हो सकता है। आप एडब्ल्यूएस लैम्ब्डा या Google क्लाउड फ़ंक्शंस पर सेवा की मेजबानी कर सकते हैं और एक HTTP कॉल के साथ सेवा का आह्वान कर सकते हैं।

const express = require("express");
const chromium = require("chrome-aws-lambda");

const app = express();

app.use(express.json());
app.use(express.urlencoded({ extended: false }));

const html2pdf = async (html) => {
  const browser = await chromium.puppeteer.launch({
    args: chromium.args,
    executablePath: await chromium.executablePath,
    headless: true,
    ignoreHTTPSErrors: true,
  });

  const page = await browser.newPage();

  await page.setContent(html, {
    waitUntil: ["networkidle0", "load", "domcontentloaded"],
    timeout: 30000,
  });

  const pdf = await page.pdf({
    format: "A4",
    printBackground: true,
  });

  await browser.close();

  return pdf;
};

app.post("/pdf", async (request, response) => {
  try {
    const { content } = request.body;
    const pdf = await html2pdf(content);
    response.contentType("application/pdf");
    response.status(200).send(pdf);
  } catch (f) {
    response.status(500).send(f.message);
  }
});

const PORT = process.env.PORT || 8080;

app.listen(PORT, async () => {
  console.log(`App listening on port ${PORT}`);
});

Leave a Comment