Sysrq147
Sysrq147

Reputation: 1367

PDFKit - Text over rectangle

Is it posible to render text over rectangle using PDFKit. Maybe it is possible to use hack, to have fill of the rectangle with opacity - but I don't want to use it that way. My text is hidden by rectangle (I am creating table by alternating rectangles with different colors).

UPDATE

I figured out that text is somehow same color as rectangles, that is probably why I don't see it. But why ?

 var doc = new PDFDocument({
    size: 'A4',
    margin: 25
  });
  doc.fontSize(11);
  doc.lineWidth(0.5);

  const projects = Projects.find().fetch();

  const rectXOffset = 25;
  const rectYOffset = 25;
  let rectPosition = 25;

  let counter = 0;

  for (var project of projects) {


    if (counter % 2 == 0)
    {

     doc.rect(rectXOffset, rectPosition, doc.page.width - rectXOffset * 2, 25).fill("#ddd");

    }
    else
    {

      doc.rect(rectXOffset, rectPosition, doc.page.width - rectXOffset * 2, 25).fill("#c9c9c9");
    }

    rectPosition += rectYOffset;
    counter++;

    doc.text(project.projectName,100,100).fillColor("red");

  }


  doc.write(process.env.PWD + '/PDFKitExampleServerSide.pdf');

Upvotes: 7

Views: 12966

Answers (3)

Chillz
Chillz

Reputation: 199

You just need to swop the maround

doc.text(project.projectName,100,100).fillColor("red");

should be

doc.fillColor("red").text(project.projectName,100,100);

By the time pdfkit is setting the text, the fill colour has been set to the colour of the rect already.

Upvotes: 1

Guntram Blohm
Guntram Blohm

Reputation: 9819

You need to use the fill and / or stroke methods to actually draw the rectangle, then redefine the colors for the text to come. This works for me to draw red text in a grey box that has a black border:

    doc.rect(45, 165, 240, 22).fillAndStroke('#ddd', '#000');
    doc.fill('#F00').stroke();
    doc.fontSize(16);
    doc.text("Sample text", 50, 170, {lineBreak: false} );

This is because doc.text doesn't pass a color, so it uses the old one.

Upvotes: 12

miirumatsu
miirumatsu

Reputation: 1

came here to search for answer to similar question... I think I've figured it out.

var doc = new PDFDocument({
    size: 'A4',
    margin: 25
});
doc.fontSize(11);
doc.lineWidth(0.5);

const projects = Projects.find().fetch();

const rectXOffset = 25;
const rectYOffset = 25;
let rectPosition = 25;

let counter = 0;

for (var project of projects) {

//here
doc.save

if (counter % 2 == 0)
{
    doc.rect(rectXOffset, rectPosition, doc.page.width - rectXOffset * 2, 25).fill("#ddd");
}
else
{
    doc.rect(rectXOffset, rectPosition, doc.page.width - rectXOffset * 2, 25).fill("#c9c9c9");
}

rectPosition += rectYOffset;
counter++;

//and here
doc.restore

doc.text(project.projectName,100,100).fillColor("red");

}


doc.write(process.env.PWD + '/PDFKitExampleServerSide.pdf');

Upvotes: 0

Related Questions