使用js在线将pdf转为图片

纯前端实现PDF文档转换为图片的功能,无需后端支持。利用PDF.js库加载并渲染PDF页面到Canvas上,支持翻页及下载为图片。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

纯前端js,不用后端代码,即可将pdf转为图片。

在线demo地址

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale = 1.0, maximum-scale = 1.0, user-scalable=no"
    />
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
    <script src="./scripts/pdf.js"></script>
    <script src="./scripts/pdf.worker.js"></script>
    <link rel="stylesheet" href="./styles/style.css" />
  </head>

  <body>
    <header>
      <div>
        <img src="./resources/safekey.png" alt="Bermuda Government Logo" />
        <h4>PDF Document to Image Converter</h4>
      </div>
      <img
        id="bm-logo"
        src="./resources/bm-logo.png"
        alt="Bermuda Government Logo"
      />
    </header>
    <div id="container">
      <div id="pdf-main-container">
        <div id="pdf-loader">
          <div class="lds-ring">
            <div></div>
            <div></div>
            <div></div>
            <div></div>
          </div>
        </div>
        <div id="pdf-contents">
          <canvas
            style="display: none !important"
            id="pdf-canvas"
            width="600"
          ></canvas>
          <div id="page-loader">
            <div class="lds-ring">
              <div></div>
              <div></div>
              <div></div>
              <div></div>
            </div>
          </div>
          <div
            style="
              display: flex;
              max-width: 600px;
              flex-wrap: wrap;
              margin-bottom: 2rem;
            "
          >
            <p
              id="info-text"
              style="
                text-align: center;
                padding: 1rem 1rem;
                max-width: 360px;
                margin: 0 auto;
                padding-bottom: 1rem;
                font-weight: 500;
                width: 100%;
              "
            >
              Select your PDF Document to convert it into an image
            </p>
            <a id="download-image" href="#">
              <img src="./resources/download.svg" alt="download" />
              Download Image</a
            >
            <div><button type="button" id="pdf-prev">prev</button> </div>
            <div><button type="button" id="pdf-next">next</button> </div>
            <button id="upload-button">
              <img id="upload-img" src="./resources/file.svg" alt="download" />
              <p id="upload-img-text">Select PDF</p>
            </button>
            <input type="file" id="file-to-upload" accept="application/pdf" />
            <div
              id="return-home-container"
              style="width: 100%; margin-top: 1.5rem; display: none"
            >
              <a id="return-home" href="#">
                <img
                  style="width: 18px; height: 18px"
                  src="./resources/arrow.svg"
                  alt="go back"
                />
                Go back to SafeKey Wallet</a
              >
            </div>
          </div>
        </div>
      </div>
    </div>
    <div id="preload01"></div>
    <div id="preload02"></div>

    <script src="./scripts/script.js"></script>
  </body>
</html>

 script.js

var __PDF_DOC,
  __CURRENT_PAGE,
  __TOTAL_PAGES,
  __PAGE_RENDERING_IN_PROGRESS = 0,
  __CANVAS = $("#pdf-canvas").get(0),
  __CANVAS_CTX = __CANVAS.getContext("2d");
// const pageLocation = window.location.origin;
// console.log(pageLocation);
// const returnHome = document.getElementById("return-home");
document.getElementById("return-home").href = window.location.origin;

$("#download-image").hide();

function showPDF(pdf_url) {
  $("#pdf-loader").show();

  PDFJS.getDocument({ url: pdf_url })
    .then(function (pdf_doc) {
      __PDF_DOC = pdf_doc;
      __TOTAL_PAGES = __PDF_DOC.numPages;

      // Hide the pdf loader and show pdf container in HTML
      $("#pdf-loader").hide();
      $("#pdf-contents").show();
      $("#pdf-total-pages").text(__TOTAL_PAGES);

      // Show the first page
      showPage(1);
    })
    .catch(function (error) {
      // If error re-show the upload button
      $("#pdf-loader").hide();
      $("#upload-button").show();

      alert(error.message);
    });
}

function showPage(page_no) {
  __PAGE_RENDERING_IN_PROGRESS = 1;
  __CURRENT_PAGE = page_no;

  // Disable Prev & Next buttons while page is being loaded
  $("#pdf-next, #pdf-prev").attr("disabled", "disabled");

  // While page is being rendered hide the canvas and show a loading message
  $("#pdf-canvas").hide();
  $("#page-loader").show();
  $("#download-image").hide();

  // Update current page in HTML
  $("#pdf-current-page").text(page_no);

  // Fetch the page
  __PDF_DOC.getPage(page_no).then(function (page) {
    // As the canvas is of a fixed width we need to set the scale of the viewport accordingly
    var scale_required = __CANVAS.width / page.getViewport(1).width;

    // Get viewport of the page at required scale
    var viewport = page.getViewport(scale_required);

    // Set canvas height
    __CANVAS.height = viewport.height;

    var renderContext = {
      canvasContext: __CANVAS_CTX,
      viewport: viewport,
    };

    // Render the page contents in the canvas
    page.render(renderContext).then(function () {
      __PAGE_RENDERING_IN_PROGRESS = 0;

      // Re-enable Prev & Next buttons
      $("#pdf-next, #pdf-prev").removeAttr("disabled");

      // Show the canvas and hide the page loader
      $("#pdf-canvas").show();
      $("#page-loader").hide();
      $("#download-image").show();
      $("#info-text").html("Download Your Image");
      $("#upload-img-text").html("Choose another PDF");
      $("#upload-button").css("width", "200");
      $("#return-home-container").show();
      setTimeout(function () {
        window.scrollTo({
          top: document.body.scrollHeight,
          behavior: "smooth",
        });
      }, 250);
    });
  });
}

// Upon click this should should trigger click on the #file-to-upload file input element
// This is better than showing the not-good-looking file input element
$("#upload-button").on("click", function () {
  $("#file-to-upload").trigger("click");
});

// When user chooses a PDF file
$("#file-to-upload").on("change", function () {
  // Validate whether PDF
  if (
    ["application/pdf"].indexOf($("#file-to-upload").get(0).files[0].type) == -1
  ) {
    alert("Error: Not a PDF Document.");
    return;
  }

  // Send the object url of the pdf
  showPDF(URL.createObjectURL($("#file-to-upload").get(0).files[0]));
});

// Previous page of the PDF
$("#pdf-prev").on("click", function () {
  if (__CURRENT_PAGE != 1) showPage(--__CURRENT_PAGE);
});

// Next page of the PDF
$("#pdf-next").on("click", function () {
  if (__CURRENT_PAGE != __TOTAL_PAGES) showPage(++__CURRENT_PAGE);
});

// Download button
$("#download-image").on("click", function () {
  $(this)
    .attr("href", __CANVAS.toDataURL())
    .attr("download", "safekey-upload-me.png");
});

const uploadBtn = document.getElementById("upload-button");

uploadBtn.addEventListener("mouseenter", () => {
  document.getElementById("upload-img").src = "./resources/file-white.svg";
});
uploadBtn.addEventListener("mouseleave", () => {
  document.getElementById("upload-img").src = "./resources/file.svg";
});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值