Geoff
Geoff

Reputation: 6639

Jspdf floating items to the right

Am tryinng to align some items to the right and incase of lengthy texts extend it to the left

SO i have added

///others

doc.setFontType("bold");
doc.setFontSize(9);
doc.setTextColor("#52575A")
doc.text(doc.internal.pageSize.getWidth()-70, 17, "Email: [email protected]");
doc.text(doc.internal.pageSize.getWidth()-70, 22, "Tel: 83473487348347834734843");
doc.textWithLink('Website: https://test.test.com',doc.internal.pageSize.getWidth()-70 , 27, { url: 'https://ecommerce.soradius.co.ke' });
 doc.save('test.pdf')

The above code generates a pdf enter image description here

From the above code am aligning my texts to the left by setting it 70px from the page width.

When the text on the email increases its cropped away. How can i set the text to the right and make it expand to the left.

I have checked This question but still doesnt align correctly

Upvotes: 0

Views: 1931

Answers (2)

kra
kra

Reputation: 1

Hope this answers helps for someone facing the same issue

    var str = 'Page 1 of 1'
    var pageSize = doc.internal.pageSize
    var pageHeight = pageSize.height ? pageSize.height : pageSize.getHeight()
    var pageWidth = doc.internal.pageSize.width || doc.internal.pageSize.getWidth();
    var txtwidth = doc.getTextWidth(str);               
    doc.text(str, pageWidth - (data.set`enter code here`tings.margin.left * 2) - txtwidth, pageHeight - 10)
[Got Expected Output][1] [1]: https://i.sstatic.net/jKAxi.png

Upvotes: 0

Naga Sai A
Naga Sai A

Reputation: 10975

To achieve expected result, use below option of using jspdf units and doc.getTextWidth() to calculate email text width

  1. Calculate difference of text width and 70 and using for spacing will avoid cropping of text
  2. Adjusting spacing with text width will avoid spacing on other text sections

var content = document.getElementById('txtContent'),
button = document.getElementById('btnDownload');

function generatePDF(){
  var doc = new jsPDF('p', 'mm','a4');

doc.setFontType("bold");
doc.setFontSize(9);
doc.setTextColor("#52575A")
  let width = doc.internal.pageSize.getWidth()
  let emailText = "Email: [email protected]"
  let txtWidth = doc.getTextWidth(emailText) > 70 ? doc.getTextWidth(emailText) - 70: 0;
  console.log("width", width, txtWidth)
doc.text(width - 70 - Math.ceil(txtWidth), 17, emailText);
doc.text(width-70, 22, "Tel: 83473487348347834734843");
doc.textWithLink('Website: https://test.test.com',width-70 , 27, { url: 'https://ecommerce.soradius.co.ke' });
 doc.save('test.pdf')
}

button.addEventListener('click', generatePDF);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
<h1>jsPDF Demo</h1>

<textarea id="txtContent" cols="60" rows="15"></textarea>
<br />
<button id="btnDownload"> Download PDF </button>

codepen- https://codepen.io/nagasai/pen/yrxZOY

Upvotes: 1

Related Questions