如何为 iOS 的 React Native 项目指定 pdf 打印的名称

问题描述 投票:0回答:2

我同时使用

expo-print
expo-sharing
来保存文件。

const { uri } = await Print.printToFileAsync({html});
await shareAsync(uri, { UTI: ".pdf", mimeType: "application/pdf" });

默认情况下它使用UUID,我想指定文件,例如,

abc.pdf
,但我没有看到文档有任何选项来设置文件名。

react-native pdf
2个回答
5
投票

我找到了答案在这里

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)
}

0
投票

  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);
    }
  };

  

© www.soinside.com 2019 - 2024. All rights reserved.