JavaScript - 将抽认卡创建为PDF

时间:2018-06-03 18:46:18

标签: javascript html json pdf

我有一个JSON对象,我需要以flashcards的格式转换为可下载的PDF文件。以下是JSON的一个示例:

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

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

如何从JSON对象生成PDF?

1 个答案:

答案 0 :(得分: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