Skip to content

Instantly share code, notes, and snippets.

@glebov21
Created March 17, 2023 11:10
Show Gist options
  • Save glebov21/cb4ca886de89970f77df2858b9fb93a8 to your computer and use it in GitHub Desktop.
Save glebov21/cb4ca886de89970f77df2858b9fb93a8 to your computer and use it in GitHub Desktop.
Save svg to pdf by jspdf
let svgEl = drawdiv.children[1];
//Если черный квадрат, то убрать прозрачность на none
svg2pdf(svgEl, pdf, {
xOffset: this.pdfPageDefaultOffsetX,
yOffset: pdfOffsetY,
scale: divToPdfRatio
});
let prevFontSize = pdf.internal.getFontSize();
let isBreadcrumbs = true; //First div = breadcrums
for (let child of drawdiv.children) {
if (child.tagName === 'DIV') {
let fontSize = prevFontSize;
if (child.style.fontSize) {
let stylefontsize = child.style.fontSize;
fontSize = Number(stylefontsize.substring(0, stylefontsize.length - 2));
}
if (isBreadcrumbs) {
pdf.setFontSize(8);
pdf.setFont(this.normalFont, "bold");
} else {
pdf.setFontSize((fontSize * divToPdfRatio));
pdf.setFont(this.normalFont, "normal");
}
let divSelector = child.querySelector('div');
let imgSelector = child.querySelector('img');
if (imgSelector) {
let imgHeight = imgSelector.height * divToPdfRatio;
let imgWidth = imgSelector.width * divToPdfRatio;
try {
pdf.addImage(imgSelector.src, "png",
this.pdfPageDefaultOffsetX + (child.offsetLeft * divToPdfRatio) - (imgWidth / 2),
pdfOffsetY + (child.offsetTop * divToPdfRatio) - (imgHeight / 2),
imgWidth, imgHeight, undefined, 'FAST');
} catch (e) {
console.error(e)
}
} else if (divSelector) {
//note: textContent почему-то не содержит \b или <br>
let innerText = divSelector.textContent;
if (!divSelector.innerHTML.includes("class")) //чтобы исключить breadcrumb или сложные
innerText = replaceHtmlEntites(divSelector.innerHTML.replace(/<br\s*[\/]?>/gi, "\n"));
if (innerText) {
innerText = innerText.trim();
let childSizes = child.getBoundingClientRect();
let splitText = innerText;
if (isBreadcrumbs)
splitText = pdf.splitTextToSize(innerText, this.pageRealWidth - (this.pdfPageDefaultOffsetX * 2));
else
splitText = pdf.splitTextToSize(innerText, ((childSizes.width + (fontSize)) * divToPdfRatio));
let textHeight = pdf.getTextDimensions(splitText).h;
let singleLine = splitText.length <= 1;
let textPositionTop = pdfOffsetY + ((child.offsetTop
+ (fontSize / 1.2 * singleLine)
- (textHeight * 1.2 / 2)
+ (fontSize / 2 * (1 - singleLine))) * divToPdfRatio);
if (child.style.color) {
let rgb = RGBvalues.color(child.style.color);
pdf.setTextColor(rgb.r, rgb.g, rgb.b);
}
try {
//scale exception?
pdf.text(this.pdfPageDefaultOffsetX + (child.offsetLeft * divToPdfRatio), textPositionTop, splitText, {
align: child.style.textAlign,
});
} catch (e) {
console.error(e)
}
pdf.setTextColor(0, 0, 0);
}
}
if (isBreadcrumbs)
isBreadcrumbs = false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment