I am trying to create an html content from json data in react native. Basically i want to generate PDF from html content which i have already done using static html content in my react native app, but now we want to generate pdf with dynamic content and decide the data to be in json and convert them into html content and then generate pdf from the html content.
Our web team has already done this rendering the json data into dom and then generating pdf from the dom using react.
Is it possible to achieve the same using react native.
CodePudding user response:
You can achieve this like doing this- (use backticks instead of single or dubble quotes)
const JsonData = {
title: 'My PDF File',
image: 'https://raw.githubusercontent.com/AboutReact/sampleresource/master/pdf.png'
}
const html = `
<html>
<head>
<meta charset="utf-8">
<title>MyPDF</title>
<style>${htmlStyles}</style>
</head>
<body>
<h1>${JsonData.title}</h1>
<img src=`${JsonData.image}` />
{JsonData.otherData}
</body>
</html>
`;
Checkout example for this: https://github.com/vishalpwr/react-native/tree/master/CreatePdf
CodePudding user response:
There is an expo plugin that should handle your use case: https://docs.expo.dev/versions/latest/sdk/print/
// generate or obtain from the server an html string
const html = `
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no" />
</head>
<body style="text-align: center;">
<h1 style="font-size: 50px; font-family: Helvetica Neue; font-weight: normal;">
Hello Expo!
</h1>
<img
src="https://d30j33t1r58ioz.cloudfront.net/static/guides/sdk.png"
style="width: 90vw;" />
</body>
</html>
`;
// Call this async function wherever you need it
Print.printToFileAsync({
html,
});