non
non

Reputation: 61

react-pdf utf8 font not working when on-fly-rendering, but works fine when render

My problem is i'm trying to save pdf file with 'on-fly-rendering' and utf8 font not working. But when displaying same pdf in render works fine.

Create pdf:

Font.register({
  family: "Roboto",
  src:
    "https://cdnjs.cloudflare.com/ajax/libs/ink/3.1.10/fonts/Roboto/roboto-light-webfont.ttf"
});

const styles = StyleSheet.create({
  page: {
    flexDirection: 'row',
    backgroundColor: '#E4E4E4',
    fontFamily: "Roboto",
    
  },
  section: {
    margin: 10,
    padding: 10,
    flexGrow: 1
  }
});

Showing and saving pdf:

              <PDFViewer>
                <MyDocument data={data} />
              </PDFViewer>
              <PDFDownloadLink document={<MyDocument data={data}/>} fileName="lista_składników.pdf">
            {({ blob, url, loading, error }) => (loading ? 'Loading document...' : 'zapisz pdf')}
          </PDFDownloadLink>

Output with PDFViewer: enter image description here

Output with PDFDownloadLink:enter image description here

Upvotes: 2

Views: 2272

Answers (2)

sergei
sergei

Reputation: 823

I had the same problem when only the first PDFDownloadLink has registered fonts. In the second one the fonts don't work.

I ended up using a better approach - generate a PDF on a button click as opposed to when a component loads.

https://github.com/diegomura/react-pdf/issues/736

import { saveAs } from 'file-saver';
import { pdf, Page, Text, View, Document } from '@react-pdf/renderer';

const generatePdfDocument = async (fileName, pdfDocumentComponent) => {
    const blob = await pdf(pdfDocumentComponent).toBlob();
    saveAs(blob, fileName);
};

const MyDocument = () => (
    <Document>
        <Page size="A4">
            <View>
                <Text>Section #1</Text>
            </View>
        </Page>
    </Document>
);

const DownloadButton = () => (
    <button
        type="button"
        onClick={() => {
            generatePdfDocument('MyDocument.pdf', <MyDocument />);
        }}
    >
        Download PDF
    </button>
);

export default DownloadButton;

Upvotes: 2

HanaKenzou
HanaKenzou

Reputation: 41

Use the Google fonts .ttf url as your src.

E.g For the Roboto light font, you can get that by doing:

curl https://fonts.googleapis.com/css2?family=Roboto:wght@300&display=swap

It should return

@font-face {
  font-family: 'Roboto';
  font-style: normal;
  font-weight: 300;
  src: url(https://fonts.gstatic.com/s/roboto/v29/KFOlCnqEu92Fr1MmSU5vAw.ttf) format('truetype');
}

Use https://fonts.gstatic.com/s/roboto/v29/KFOlCnqEu92Fr1MmSU5vAw.ttf as your src

Upvotes: 0

Related Questions