【问题标题】:JavaScript - Create flashcards to PDF [closed]JavaScript - 将抽认卡创建为 PDF [关闭]
【发布时间】:2018-06-03 18:46:17
【问题描述】:

我有一个 JSON 对象,我需要将其转换为抽认卡格式的可下载 PDF 文件。这是 JSON 的示例:

{
    questions : [
        {"front": "ABC", "back" : "DEF"},
        {"front": "HIJ", "back" : "KLM"},
        {"front": "NOP", "back" : "QRS"}
    ]
}

抽认卡应位于 2 列 3 行的表格中。左边是ABC等,右边是DEF等

如何从 JSON 对象生成 PDF?

【问题讨论】:

    标签: javascript html json pdf


    【解决方案1】:

    您可以打开一个新窗口,并将其打印为 PDF: JSFiddle

    (一定要允许弹窗,否则无法使用。)


    let questions = [
              {"front": "ABC", "back" : "DEF"},
              {"front": "HIJ", "back" : "KLM"},
              {"front": "NOP", "back" : "QRS"}
          ];
    function printCards() {
      let container = document.createElement("div");
      questions.forEach(question => {
        let card = document.createElement("div");
        card.classList.add("card");
        let front = document.createElement("div");
        front.classList.add("front");
        front.textContent = question.front;
        card.appendChild(front);
        let back = document.createElement("div");
        back.classList.add("back");
        back.textContent = question.back;
        card.appendChild(back);
        container.appendChild(card);
      });
      let style = document.getElementById('style');
      let printWindow = window.open("", "print", "");
      printWindow.document.open();
      printWindow.document.write(container.outerHTML + style.outerHTML);
      printWindow.document.close();
      printWindow.print();
    }
    

    <style id="style">
      div.card {
        border: 1px solid black;
        width: 12cm;
      }
      div.card > div {
        display: inline-block;
        height: 4cm;
        width: 6cm;
      }
      div.front {
        background-color: green;
      }
      div.back {
        background-color: red;
      }
    </style>
    <button onclick="printCards();">Print</button>
    

    默认情况下,大多数浏览器会在打印时移除背景颜色。您可以通过更改设置来保留背景图形:

    Chrome

    Firefox

    【讨论】:

    • 当我点击代码中的按钮时,我会被带到带有要打印的卡片的页面,但是颜色丢失并且一些边框消失了。有没有办法防止这种情况发生?
    • @marmadukeandbob 我编辑了我的答案。
    • 如果程序由任何人运行,他们都必须这样做吗?有没有办法默认启用它?
    • 另外,有些边框还是隐藏的
    猜你喜欢
    • 2017-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-26
    • 2014-01-19
    • 2010-12-13
    • 2010-09-07
    • 2016-06-07
    相关资源
    最近更新 更多