简体   繁体   中英

add title when saving element as pdf

I have this function which is used across different elements:

function saveAsPDF(chartID) {
  let canvas = document.querySelector('#' + chartID); //Charts ID
  
  //creates image
  let canvasImg = canvas.toDataURL("image/png", 1.0); 

  //Changing the image file to JPEG will result in the PDF having a black background
            
  //creates PDF from img
  let doc = new jsPDF('landscape'); // page orientation.
  doc.setFontSize(12); //Edit the font size that appears on the PDF.
  doc.text(15, 15, chartID);   // push title right, push title down.
  doc.addImage(canvasImg, 'PNG', 10, 20, 280, 150 ); // push right, push down, stretch horizontal, stretch vertical
  doc.save( chartID +'.pdf');
}

currently the doc.text shows the id as the title. but the issue is it appears LikeThis, when we need it to appear Like This, with spacing. as you cant have spaces in the id, how else can I my text to show space. I cant simply do

doc.text(15, 15, 'chart Name')

as the function is used across different things, any idea on how when i click to saveasPDF, the text changes to to signify the particular element being saved?

Each thing this hits has a

<p class="h4 card-header-title">
  Title
</p>

is there a way to grab this?

What about keeping using the ID but adding a space in front of each capital letter, as explained in this answer: https://stackoverflow.com/a/25452019/14201528 ?

doc.text(15, 15, chartID.replace(/([AZ])/g, ' $1').trim());

If you prefer to use the title written in the paragraph, you should be able to access it like this:

const cartTitle = document.querySelector("#" + chartId + " > p.card-header-title").innerHTML;

but the <p> element should not contain any child element or you will see the tags in your title:

 const chartId1 = 'firstdiv'; const chartId2 = 'seconddiv'; console.log(document.querySelector("#" + chartId1 + " > p.card-header-title").innerHTML); console.log(document.querySelector("#" + chartId2 + " > p.card-header-title").innerHTML);
 <div id="firstdiv"> <p class="h4 card-header-title">Title 1</p> </div> <div id="seconddiv"> <p class="h4 card-header-title"><strong>Title 1</strong></p> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM