wojtekmaj / react-pdf

Display PDFs in your React app as easily as if they were images.
https://projects.wojtekmaj.pl/react-pdf
MIT License
9.11k stars 867 forks source link

setting canvas font does not set font until after canvas is rendered - missing hook? #1669

Closed cindyloo closed 8 months ago

cindyloo commented 8 months ago

Before you start - checklist

Description

my assumption is that getting the canvas context from Page and setting it means that I can alter the font ( looking at the example here: https://jsfiddle.net/cxrznbso/1/ ). However, it appears that any of my changes apply to after the first writing to the canvas. I realize I don't exactly know how the PDF text is rendered to the canvas, but it seems that inside PageCanvas there would be the options to pass in a Font spec inside function drawPageOnCanvas()?

Is there a way to override the default 'system' font in canvas after the loading of the PDF and before the content is first rendered? I've tried almost all the handlers that are exposed to Page

thank you

Steps to reproduce

use a callback handler to try to change canvas font

   async function onLoadSuccess(page) {
    console.log("LoadSuccess", page);

      const cv = canvas.current as any;
      if (!!cv){
        const ctx = (cv as HTMLCanvasElement)?.getContext("2d");
          if (!!cv && !!ctx){
            ctx.font = "16px Courier";
        }
      }
   }

 <Page
        className="test"
        canvasRef={canvas}
          key={`page-${index}`}
          onLoadSuccess={onLoadSuccess}
          onRenderTextLayerSuccess={onRenderTextLayerSuccess}
          customTextRenderer={onCustomTextRendererSuccess}
          onGetTextSuccess={onGetTextSuccess}
          onRenderSuccess={onPageRenderSuccess}
          pageIndex={scrollToPage + index -1} // CSB needs to change so we can scroll back one page. not great
          width={containerWidth ? Math.min(containerWidth, maxWidth) : maxWidth}

        />

Expected behavior

I would think that instead of the system font, I'd have the text in the desired Courier font:

Actual behavior

Screenshot 2023-11-21 at 12 16 46 PM

Additional information

No response

Environment

cindyloo commented 8 months ago

addendum, I also hid the canvas just to see if the textLayer would look ok with the new font. It has some skips and overwritings, so I don't think that is the right way to do it?

wojtekmaj commented 8 months ago

You can't alter PDF font. PDF.js will set a font for each node it renders. You can only set font for stuff you render yourself, like a watermark.