skip to Main Content

Rectangle has a black background when pdf is set on a unit of inches. I want it just blank rectangle with a thin black outline, can’t change it into a different unit because most of my work depends on inches unit. When it is created in a pdf, it turns into a box overlapped in black background.

const pdf = new jsPDF({
  unit: 'in',  // Set the unit to inches
  format: 'letter' // 'letter' format is 8.5 x 11 inches
});
const x = 1;   
const y = 1;  
const width = 4;  
const height = 2; 
pdf.setFillColor(0, 0, 0); 
pdf.rect(x, y, width, height);

2

Answers


  1. You call setFillColor before drawing the rectangle. If you want to draw just an outline of the rectangle without any fill color, you should use the rect method with the draw parameter set to S (for stroke only):

    I could not get your version of jsPDF to wrok, an older one did (but not here at SO, due to sandbox issues)

    document.addEventListener('DOMContentLoaded', () => {
      const pdf = new jsPDF({
        unit: 'in', // Set the unit to inches
        format: 'letter' // 'letter' format is 8.5 x 11 inches
      });
      const x = 1;
      const y = 1;
      const width = 4;
      const height = 2;
      pdf.setDrawColor(0, 0, 0); // Set the color for the rectangle outline (black)
      pdf.rect(x, y, width, height, 'S'); // Draw the rectangle with only the outline ('S' stands for Stroke)
      window.open(pdf.output('bloburl'))
    });
    
    <!--script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script -->
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.debug.js"></script>
    
    Login or Signup to reply.
  2. So.. that’s what I’ve got using script below
    Rectangle

    You need to add:

    pdf.setLineWidth(0.02)
    pdf.setFillColor(0, 0, 0) 
    

    to set the line width for the rectangle and to set the border color.

    In the end of pdf.rect you need to add ‘S’ as well so it will draw only border:

    pdf.rect(x, y, width, height, "S")
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search