React-Native에서 데이터 pdf로 다운 받기(react-native-html-to-pdf)

dev.horang🐯·2023년 3월 10일
2

React-Native

목록 보기
10/15
post-thumbnail

프로젝트 중 다운받은 데이터를 pdf형태로 다운받아야 하는 상황이 발생했고 라이브러리를 서치해 보다가 react-native-html-to-pdf라는 라이브러리를 발견했고 해당 라이브러리를 사용했던 건에 대한 내용이다.

일단 전체 코드 먼저

  useEffect(() => {
    navigation.setOptions({
      title: title.slice(0, 15) + '...' ,
      headerRight: () => moveOn,
    });

    const pdfData = list?.map((v) => {
      return `<tr>
                <td>${v.title}</td>
                <td>${v.artist}</td>
                <td>${v.type}</td>
              </tr>`;
    });

    const a = pdfData.join('');

    const exportPdf = async () => {
      let options = {
        html: `<div>
                    <h1>${title}</h1>
                    <h2>MODE : ${mode}</h2>
                      <table width="100%" border ="1">
                        <tr>
                        <td>title</td>
                        <td>artist</td>
                        <td>type</td>
                        </tr>
                        ${a}
                      </table>
                </div>`,
        fileName: `${title}`,
        directory: 'Documents',
      };

      let file = await reactNativeHtmlToPdf.convert(options);
      console.log(file.filePath);
      const showFile = async () =>
        await copyFile(
          'file://' + file.filePath,
          `${DownloadDirectoryPath}/${title}.pdf`,
        );

      const shareOptions = {
        title: 'Share your DownloadMusic',
        failOnCancel: false,
        url:`${encodeURI(file.filePath)}`,
        saveToFiles: true,
      };

      
      const sharePdf = async () => {
        try {
          await Share.open(shareOptions);
          setSwal(true);
          setTimeout(() => {
            setSwal(false);
          }, 2000);
        } catch (error) {
        }
      };
      
      Platform.OS == 'android' ? showFile() : sharePdf();
      
    const moveOn = (
      <Pressable style={styles.blackBox} onPress={exportPdf}>
        <Image source={assets.downloadPlaylist} style={{ zIndex: 3 }} />
      </Pressable>
    );
  }, [list, mode]);

뜯어보자면
pdfData에서 원하는 내용을 arr.map을 돌려서 모두 텍스트 형태로 추출한다.
그리고 리스트 형태로 나온 pdfData를 .join으로 하나로 합친다.
그리고 exportPdf 함수를 사용해서 위에서 가져온 내용을 옵션의 html로 변환시켜서 Documents 디렉토리에 저장한다. 여기까지만 하면 어플자체의 Directory에 저장되지만 이 폴더자체의 접근이 ios의경우엔 따로 설정해줘야하고 android의 경우도 다른 어플을 사용해야만 접근이 가능해서 이 파일을 접근 가능한 위치로 보내줘야 했다.

 let file = await reactNativeHtmlToPdf.convert(options);

로 저장된 위치의 파일을 찾고 해당 파일을 react-native-fs를 사용해서 접근가능한 폴더로 복사해 주었다.

const showFile = async () =>
        await copyFile(
          'file://' + file.filePath,
          `${DownloadDirectoryPath}/${title}.pdf`,
        );

기왕이면 특정 위치에 저장되게 직접 설정했으면 좋겠다고 생각해서 찾아봣는데 reactnative 의 자체 기능인 Share에 saveToFiles 항목으로 원하는 위치에 원하는 이름으로 저장할 수 있는것을 확인했지만 이부분은 ios에서만 가능했기 때문에 ios일때는 해당 기능이 동작하게 했다.

 const shareOptions = {
        title: 'Share your DownloadMusic',
        failOnCancel: false,
        url:`${encodeURI(file.filePath)}`,
        saveToFiles: true,
      };

      
      const sharePdf = async () => {
        try {
          await Share.open(shareOptions);
          setSwal(true);
          setTimeout(() => {
            setSwal(false);
          }, 2000);
        } catch (error) {
        }
      };
      

** 여기서 encodeURI는 IOS의 경우 파일 저장시 파일명을 인코딩 시켜서 저장하기 때문에 찾아오기 위해서는 encodeURI함수를 사용해서 찾아와야 작동된다

결과적으로 다운로드 폴더에는

이렇게 원하는 형태의 pdf가 들어오게 된다!!!!!!!!!호우!!!!!

profile
좋아하는걸 배우는건 신나🎵

0개의 댓글