我同时使用
expo-print
和 expo-sharing
来保存文件。
const { uri } = await Print.printToFileAsync({html});
await shareAsync(uri, { UTI: ".pdf", mimeType: "application/pdf" });
默认情况下它使用UUID,我想指定文件,例如,
abc.pdf
,但我没有看到文档有任何选项来设置文件名。
我找到了答案在这里
import * as Print from 'expo-print'
从“expo-sharing”导入 * 作为共享 从“expo-file-system”导入 * 作为文件系统
const printToPdf = async () => {
const response = await Print.printToFileAsync({
html: createHtmlStringForPdf(),
})
// this changes the bit after the last slash of the uri (the document's name) to "invoice_<date of transaction"
const pdfName = `${response.uri.slice(
0,
response.uri.lastIndexOf('/') + 1
)}invoice_${readableDate.getTime()}.pdf`
await FileSystem.moveAsync({
from: response.uri,
to: pdfName,
})
sharePdf(pdfName)
}
const sharePdf = (url) => {
Sharing.shareAsync(url)
}
const file name = new Date(); // Use current date for testing
const printToPdf = async () => {
setGeneratingPdf(true);
try {
const printOptions = {
html: createHtmlStringForPdf(),
};
// Generate the PDF file
const result = await Print.printToFileAsync(printOptions);
if (result && result.uri) {
// New file name
const newFileName = `${FileSystem.documentDirectory}Invoice_${readableDate.getTime()}.pdf`;
// Rename the PDF file
await FileSystem.moveAsync({
from: result.uri,
to: newFileName,
});
// Share the renamed PDF
await Sharing.shareAsync(newFileName, {
mimeType: 'application/pdf',
dialogTitle: 'Share Invoice PDF'
});
} else {
console.error('Error generating PDF:', result);
}
} catch (error) {
console.error('Error generating or sharing PDF:', error);
} finally {
setGeneratingPdf(false);
}
};