skip to Main Content

When applying an angle to a text in jsPDF, it seems that the text is rotated around its left point of its baseline, while my goal is to rotate the text around its center.

This is the code that I am applying:

// Create the jsPDF instance
doc = new jsPDF({
    orientation: 'p',
    unit: 'mm',
    format: [250, 180]
});

// Rotate the text
doc.text("Text to rotate", 80, 80, {
    angle: 45
});

// Save the document
doc.save();

In the documentation, there is no property in the text() method that allows to set the origin of the rotation as the center of the text field.

Is there a way to go around this limitation ?

2

Answers


  1. Give this a shot. It’ll calc the center and adjust it.

    // Create the jsPDF instance
    var doc = new jsPDF({
        orientation: 'p',
        unit: 'mm',
        format: [250, 180]
    });
    
    // Get the text dimensions
    var text = "Text to rotate";
    var fontSize = 12; // Adjust the font size as needed
    var textWidth = doc.getStringUnitWidth(text) * fontSize;
    var textHeight = fontSize;
    
    // Calculate the center position
    var centerX = 80 + textWidth / 2;
    var centerY = 80 + textHeight / 2;
    
    // Save the current canvas state
    doc.saveGraphicsState();
    
    // Move the origin to the center position
    doc.text(text, centerX, centerY, {
        align: 'center',
        angle: 45
    });
    
    // Restore the canvas state
    doc.restoreGraphicsState();
    
    // Save the document
    doc.save();
    
    Login or Signup to reply.
  2. You just need to add half the height of the text.

     let doc = new jsPDF({
          orientation: 'p',
          unit: 'mm',
          format: [250, 180]
      });
      
      const {h} = doc.getTextDimensions("Text to rotate");
      doc.text("Text to rotate", 0, 30+h/2, null, 10);
      doc.save("test");
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search