6. Error / / 2024. 9. 4. 16:44

[ ActiveReportsJs ] PDF 다운로드 구현과정 getDocument 매서드 문제

728x90

구현하고자 하는 기능

Reort를 PDF로 저장하는 기능 (공통으로 사용하는 기능으로, props로 받아서 공통화함)

문제

Viewer의 getDocument매서드를 불러오는데, 없다는 에러가 뜬

import React from 'react';
import { Viewer } from '@grapecity/activereports-react';
import { PdfExport, HtmlExport, TabularDataExport } from '@grapecity/activereports';

// DownloadButtonProps 인터페이스 정의
interface DownloadButtonProps {
  reportUrl: string; // 보고서 URL
  viewerRef: React.RefObject<Viewer>; // Viewer 컴포넌트에 대한 참조
}

function DownloadButton({ reportUrl, viewerRef }: DownloadButtonProps) {
  // PDF 다운로드 핸들러
  const handleDownloadPdf = async () => {
    try {
      // viewerRef.current가 유효한지 확인
      if (!viewerRef.current) {
        console.error('Viewer reference is not available.');
        return;
      }

      // Viewer로부터 문서 객체 얻기
      // getDocument 메서드를 사용하여 문서를 가져옵니다.
      const document = viewerRef.current.getDocument();
      console.log('viewerRef', viewerRef);

      if (!document) {
        console.error('Document is not available.', document);
        return;
      }

      // PDF로 내보내기 설정
      const pdfSettings: PdfExport.PdfSettings = {
        info: {
          title: 'ActiveReportsJS Sample', // 문서 제목
          author: 'GrapeCity', // 문서 저자
          subject: 'Web Reporting', // 문서 주제
          keywords: 'reporting, sample' // 문서 키워드
        },
        pdfVersion: '1.7', // PDF 버전
        autoPrint: true // 자동 인쇄 설정
      };

      // PDF로 내보내기
      const result = await PdfExport.exportDocument(document, pdfSettings);

      // 결과 다운로드
      result.download('exportedreport.pdf'); // 다운로드할 파일명
    } catch (error) {
      console.error('PDF 다운로드 중 오류가 발생했습니다:', error);
    }
  };

  return <button onClick={handleDownloadPdf}>PDF 다운로드</button>;
}

export default DownloadButton;

viewerRef는 정상적으로 콘솔에 보이는데, Document를 못불러오는 현상이 있다

 

해결

그래서 혹시나 Ref에 접근하여 Uri를 가져와서 넘겨주면 파일을 읽어서 PDF화할거같아서
const document = viewerRef.current.props.report?.Uri 로 바꾸면, 타입에러가 떠서 안되는 현상이 있다
'string' 형식의 인수는 'PageDocument | VDomRenderer' 형식의 매개 변수에 할당될 없습니다.ts(2345)

뭐지뭐지 쥐어짜고 삽질을 하다가. Core를 활용해서 보고서 URL을 로드해주고, document를 RUN해준 후 이거를 전달했더니 성공적으로 PDF다운로드가 가능해졌다!!!!

import React from 'react';
import { Viewer } from '@grapecity/activereports-react';
import { PdfExport, HtmlExport, TabularDataExport, Core } from '@grapecity/activereports';

// DownloadButtonProps 인터페이스 정의
interface DownloadButtonProps {
  reportUrl: string; // 보고서 URL
  viewerRef: React.RefObject<Viewer>; // Viewer 컴포넌트에 대한 참조
}

function DownloadButton({ reportUrl, viewerRef }: DownloadButtonProps) {
  // PDF 다운로드 핸들러
  const handleDownloadPdf = async () => {
    try {
      // viewerRef.current가 유효한지 확인
      if (!viewerRef.current) {
        console.error('Viewer reference is not available.');
        return;
      }

      // Viewer로부터 문서 객체 얻기
      console.log('viewerRef', viewerRef);

      // PageReport 인스턴스 생성 및 로드
      const report = new Core.PageReport();
      await report.load(reportUrl); // 보고서 URL 로드
      
      // 보고서 실행하여 PageDocument 얻기
      const document = await report.run(); // PageDocument 객체 반환
      console.log('viewerRef', viewerRef);
      console.log('document', document);

      if (!document) {
        console.error('Document is not available.', document);
        return;
      }
      // PDF로 내보내기 설정
      const pdfSettings: PdfExport.PdfSettings = {
        info: {
          title: 'ActiveReportsJS Sample', // 문서 제목
          author: 'GrapeCity', // 문서 저자
          subject: 'Web Reporting', // 문서 주제
          keywords: 'reporting, sample' // 문서 키워드
        },
        pdfVersion: '1.7', // PDF 버전
        autoPrint: true // 자동 인쇄 설정
      };

      // PDF로 내보내기
      const result = await PdfExport.exportDocument(document, pdfSettings);

      // 결과 다운로드
      result.download('exportedreport.pdf'); // 다운로드할 파일명
    } catch (error) {
      console.error('PDF 다운로드 중 오류가 발생했습니다:', error);
    }
  };

  return <button onClick={handleDownloadPdf}>PDF 다운로드</button>;
}

export default DownloadButton;

삽질하다가 해낸 기능이라 행복하고 기록하고자 남긴다

근데 또 해결해야할게....한글만 깨지는 현상이 있다는점^^

다음 에러 해결로 쓸 예정이다.

  • 네이버 블로그 공유
  • 네이버 밴드 공유
  • 페이스북 공유
  • 카카오스토리 공유