Skip to content

Commit

Permalink
自定义下载pdf
Browse files Browse the repository at this point in the history
  • Loading branch information
027xiguapi committed Sep 12, 2024
1 parent 84474df commit e5edd74
Show file tree
Hide file tree
Showing 6 changed files with 198 additions and 6 deletions.
13 changes: 13 additions & 0 deletions component/options/custom.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,12 @@ export default function Custom() {
})
}

function downloadPdf() {
sendToContentScript({
name: "custom-downloadPdf"
})
}

return (
<fieldset>
<legend>{i18n("customConfig")}</legend>
Expand Down Expand Up @@ -91,6 +97,13 @@ export default function Custom() {
</span>
<DownloadOutlined style={{ color: "#52c41a", fontSize: "16px" }} />
</div>
<div className="item download" onClick={downloadPdf}>
<span>
<StarTwoTone twoToneColor="#eb2f96" style={{ marginRight: "5px" }} />
{i18n("downloadPdf")}
</span>
<DownloadOutlined style={{ color: "#52c41a", fontSize: "16px" }} />
</div>
</fieldset>
)
}
30 changes: 25 additions & 5 deletions contents/custom.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { useMessage } from "@plasmohq/messaging/hook"
import { useStorage } from "@plasmohq/storage/hook"

import { addCss, saveHtml, saveMarkdown, saveTxt, setIcon } from "~tools"
import Dom2Pdf from "~utils/html2Pdf"
import Turndown from "~utils/turndown"

const turndownService = Turndown()
Expand Down Expand Up @@ -47,6 +48,10 @@ export default function Custom() {
isSelect = true
isDownloadType = "markdown"
}
if (req.name == "custom-downloadPdf") {
isSelect = true
isDownloadType = "pdf"
}
})

/* 插入自定义css代码 */
Expand Down Expand Up @@ -92,34 +97,49 @@ export default function Custom() {
document.addEventListener("mousemove", function (event) {
const target = event.target as HTMLElement

const currentList = document.querySelectorAll(".codebox-current")
currentList.forEach((el) => {
el.classList.remove("codebox-current")
})

removeCurrentDom()
isSelect && target.classList.add("codebox-current")
})
document.addEventListener("click", function (event) {
if (isDownloadType == "html") {
isSelect && downloadHtml()
} else if (isDownloadType == "markdown") {
isSelect && downloadMarkdown()
} else if (isDownloadType == "pdf") {
isSelect && downloadPdf()
}
})
}

function removeCurrentDom() {
const currentList = document.querySelectorAll(".codebox-current")
currentList.forEach((el) => {
el.classList.remove("codebox-current")
})
}

function downloadHtml() {
const currentDom = document.querySelector(".codebox-current")
removeCurrentDom()
saveHtml(currentDom, article.title)
isSelect = false
}

function downloadMarkdown() {
const currentDom = document.querySelector(".codebox-current")
removeCurrentDom()
const markdown = turndownService.turndown(currentDom)
saveMarkdown(markdown, article.title)
isSelect = false
}

function downloadPdf() {
const currentDom = document.querySelector(".codebox-current")
removeCurrentDom()
const pdf = new Dom2Pdf(currentDom, article.title)
pdf.downloadPdf()
isSelect = false
}

return <div style={{ display: "none" }}></div>
}
3 changes: 3 additions & 0 deletions locales/en/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,9 @@
"downloadHtml": {
"message": "Download HTML"
},
"downloadPdf": {
"message": "Download PDF"
},
"copyCode": {
"message": "Copy Code"
},
Expand Down
3 changes: 3 additions & 0 deletions locales/zh_CN/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,9 @@
"downloadHtml": {
"message": "下载 HTML"
},
"downloadPdf": {
"message": "下载 PDF"
},
"copyCode": {
"message": "一键复制代码"
},
Expand Down
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "code-box",
"displayName": "__MSG_extensionName__",
"version": "0.6.4",
"version": "0.6.5",
"description": "__MSG_extensionDescription__",
"author": "027xiguapi. <458813868@qq.com>",
"scripts": {
Expand Down Expand Up @@ -32,6 +32,8 @@
"antd": "^5.19.4",
"dayjs": "^1.11.12",
"file-saver": "^2.0.5",
"html2canvas": "^1.4.1",
"jspdf": "^2.5.1",
"jssha": "^3.3.1",
"plasmo": "0.89.1",
"react": "18.2.0",
Expand Down
151 changes: 151 additions & 0 deletions utils/html2Pdf.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
import dayjs from "dayjs"
import html2canvas from "html2canvas"
import jsPDF from "jspdf"

export default class Dom2Pdf {
_rootDom = null
_title = "codebox-pdf"
_a4Width = 595.266
_a4Height = 841.89
_pageBackground = "rgba(255,255,255)"
_hex = [0xff, 0xff, 0xff]

constructor(rootDom, title, color = [255, 255, 255]) {
this._rootDom = rootDom
this._title = title
this._pageBackground = `rgb(${color[0]},${color[1]},${color[2]})`
this._hex = color
}

async savePdf() {
const a4Width = this._a4Width
const a4Height = this._a4Height
const hex = this._hex

return new Promise(async (resolve, reject) => {
try {
const canvas = await html2canvas(this._rootDom, {
useCORS: true,
allowTaint: true,
scale: 0.8,
backgroundColor: this._pageBackground
})
const pdf = new jsPDF("p", "pt", "a4")
let index = 1,
canvas1 = document.createElement("canvas"),
height
let leftHeight = canvas.height

let a4HeightRef = Math.floor((canvas.width / a4Width) * a4Height)
let position = 0
let pageData = canvas.toDataURL("image/jpeg", 0.7)
pdf.setDisplayMode("fullwidth", "continuous", "FullScreen")

function createImpl(canvas) {
if (leftHeight > 0) {
index++
let checkCount = 0
if (leftHeight > a4HeightRef) {
let i = position + a4HeightRef
for (i = position + a4HeightRef; i >= position; i--) {
let isWrite = true
for (let j = 0; j < canvas.width; j++) {
let c = canvas.getContext("2d").getImageData(j, i, 1, 1).data
if (c[0] !== hex[0] || c[1] !== hex[1] || c[2] !== hex[2]) {
isWrite = false
break
}
}
if (isWrite) {
checkCount++
if (checkCount >= 10) {
break
}
} else {
checkCount = 0
}
}
height =
Math.round(i - position) || Math.min(leftHeight, a4HeightRef)
if (height <= 0) {
height = a4HeightRef
}
} else {
height = leftHeight
}
canvas1.width = canvas.width
canvas1.height = height
let ctx = canvas1.getContext("2d")
ctx.drawImage(
canvas,
0,
position,
canvas.width,
height,
0,
0,
canvas.width,
height
)
if (position !== 0) {
pdf.addPage()
}
pdf.setFillColor(hex[0], hex[1], hex[2])
pdf.rect(0, 0, a4Width, a4Height, "F")
pdf.addImage(
canvas1.toDataURL("image/jpeg", 1.0),
"JPEG",
0,
0,
a4Width,
(a4Width / canvas1.width) * height
)
leftHeight -= height
position += height
if (leftHeight > 0) {
setTimeout(createImpl, 500, canvas)
} else {
resolve(pdf)
}
}
}

if (leftHeight < a4HeightRef) {
pdf.setFillColor(hex[0], hex[1], hex[2])
pdf.rect(0, 0, a4Width, a4Height, "F")
pdf.addImage(
pageData,
"JPEG",
0,
0,
a4Width,
(a4Width / canvas.width) * leftHeight
)
resolve(pdf)
} else {
try {
pdf.deletePage(0)
setTimeout(createImpl, 500, canvas)
} catch (err) {
reject(err)
}
}
} catch (error) {
reject(error)
}
})
}

async downloadPdf() {
const newPdf = (await this.savePdf()) as jsPDF
const title = `${this._title}-${dayjs().format("YYYY-MM-DD HH:mm:ss")}.pdf`
newPdf.save(title)
}

async printPdf() {
const newPdf = (await this.savePdf()) as jsPDF
const pdfBlob = newPdf.output("blob")
const pdfUrl = URL.createObjectURL(pdfBlob)
window.open(pdfUrl)
}
}

0 comments on commit e5edd74

Please sign in to comment.