wojtekmaj / react-pdf

Display PDFs in your React app as easily as if they were images.

Home Page:https://projects.wojtekmaj.pl/react-pdf

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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

cindyloo opened this issue · comments

Before you start - checklist

  • I followed instructions in documentation written for my React-PDF version
  • I have checked if this bug is not already reported
  • I have checked if an issue is not listed in Known issues
  • If I have a problem with PDF rendering, I checked if my PDF renders properly in PDF.js demo

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

  • Browser (if applicable):Chrome
  • React-PDF version: newest
  • React version: 18
  • Webpack version (if applicable):

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?

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.