Hopding / pdf-lib

Create and modify PDF documents in any JavaScript environment
https://pdf-lib.js.org
MIT License
6.93k stars 664 forks source link

Gradient issue, with strokeWidth, scaling, gradient failure, no scaling, gradient success. #1431

Open zzggbond opened 1 year ago

zzggbond commented 1 year ago

What were you trying to do?

Hello, I would like to have rect (with strokeWidth) gradient in the generated PDF after scaling.

How did you attempt to do it?

const express = require('express'); const Canvas = require('canvas'); const fs = require('fs'); const { PDFDocument }= require('pdf-lib');

const app = express() app.listen(8080,()=>{ console.log('running in http://127.0.0.1:8080') })

app.get('/test',async(req,res) => { const file = "./"+Math.random()+".pdf"

const canvas = Canvas.createCanvas(300, 300, 'pdf');
const ctx = canvas.getContext("2d");
const grad = ctx.createLinearGradient(0, 0, 300, 0);
grad.addColorStop(0, "green");
grad.addColorStop(1, "blue");
ctx.fillStyle = grad;
ctx.fillRect(10, 10, 150, 100);
// set stroke
ctx.lineWidth = 1;
ctx.strokeStyle = "red";
ctx.strokeRect(10, 10, 150, 100);

const buffer = canvas.toBuffer('application/pdf');

var pdfDoc=await PDFDocument.load(buffer);
const pdfPage=pdfDoc.getPage(0);
// scale
// pdfPage.scale(1, 1);
pdfPage.scale(0.1, 0.1);
const pdfBytes = await pdfDoc.save()

await fs.promises.writeFile(file, pdfBytes)
res.setHeader('Content-Type', 'application/json')
res.end(JSON.stringify({ok:'ok'}))

})

What actually happened?

The first scenario: with strokeWidth, a 0.1 scale is applied, and the rect generated in the PDF will not gradient. Without scaling, it will gradient; The second scenario: without strokeWidth, there will be a gradient with or without scaling; So is there a conflict between scaling and strokeWidth? SUCCESS success FAILURE failure

What did you expect to happen?

In the case of both scaling and strokeWidth, I want the rect generated in the PDF to gradient. Thank you.

How can we reproduce the issue?

Examples are as follows

  1. npm install
  2. npm run test
  3. http://127.0.0.1:8080/test download test.zip

Version

1.17.1

What environment are you running pdf-lib in?

Node

Checklist

Additional Notes

Thank you.