Reactjs,生成pdf文件,设置文件名



是否可以在"react pdf/renderer":"2.3.0";?

当我点击工具栏中的下载时,它可能会保存为uid名称:现在它设置例如";f983dad0-eb2c-480b-b3e9-574d71ab162b.pdf";。文件生成正确。我想将文件的名称更改为例如";name.pdf";。

我使用";反应":"17.0.2〃;。

import { PDFViewer } from '@react-pdf/renderer';
const App = () => (
<PDFViewer 
//src="/name.pdf" <- not working, error: Property 'src' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<PDFViewer> & Readonly<PDFViewerProps> & Readonly<...>'.
//fileName="/name.pdf" <- not working, error: Property 'fileName' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<PDFViewer> & Readonly<PDFViewerProps> & Readonly<...>'.
showToolbar={true} 
style={{ height: "45vh", width: "100%" }}
>
<MyDocument />
</PDFViewer>
);

您可以使用文件保护程序包中的saveAs函数将<Document />保存为具有自定义名称的blob。看一下saveFile函数。

import { PDFViewer } from "@react-pdf/renderer";
import {
pdf,
Document,
Page,
Text,
View,
StyleSheet
} from "@react-pdf/renderer";
import { saveAs } from "file-saver";
const styles = StyleSheet.create({
page: {
flexDirection: "row",
backgroundColor: "#E4E4E4"
},
section: {
margin: 10,
padding: 10,
flexGrow: 1
}
});
const MyDocument = () => (
<Document>
<Page size="A4" style={styles.page}>
<View style={styles.section}>
<Text>Section #1</Text>
</View>
<View style={styles.section}>
<Text>Section #2</Text>
</View>
</Page>
</Document>
);
export default function App() {
const saveFile = () => {
// This does the trick!
pdf(<MyDocument />)
.toBlob()
.then((blob) => saveAs(blob, "YourFileName.pdf"));
};
return (
<div>
<PDFViewer>
<MyDocument />
</PDFViewer>
<div>
<button onClick={saveFile}>Save File</button>
</div>
</div>
);
}

最新更新