>  기사  >  웹 프론트엔드  >  PWA 문서 스캐너를 구축하는 방법: PDF로 캡처, 편집 및 업로드

PWA 문서 스캐너를 구축하는 방법: PDF로 캡처, 편집 및 업로드

Susan Sarandon
Susan Sarandon원래의
2024-10-25 06:34:02575검색

많은 산업 분야에서 송장영수증과 같은 문서를 캡처, 편집하고 클라우드에 업로드하려면 문서 스캐너 앱이 필수적입니다. Dynamsoft Document Viewer SDK를 활용하면 사용자가 이미지를 캡처하고, 자르고, 여러 페이지를 단일 문서로 결합할 수 있는 프로그레시브 웹 앱(PWA) 문서 스캐너를 구축할 수 있습니다. 스캔한 문서를 PDF 형식으로 변환하여 쉽게 공유하고 저장할 수 있습니다. 이 튜토리얼은 Dynamsoft Document Viewer SDK를 사용하여 PWA 문서 스캐너를 만드는 과정을 안내합니다.

PWA 문서 스캐너 데모 비디오

전제 조건

  • Dynamsoft Document Viewer: 이 패키지는 JPEG, PNG, TIFF, BMP. 주요 기능에는 PDF 렌더링, 페이지 탐색, 이미지 품질 향상 및 문서 저장 기능이 포함됩니다. npm에서 SDK를 찾을 수 있습니다.

  • Dynamsoft Capture Vision 평가판 라이센스: Dynamsoft SDK의 모든 기능에 대한 액세스를 제공하는 30일 무료 평가판 라이센스

PDF 파일 업로드를 위한 웹 서버 생성

Base64 문자열을 수신하고 이를 PDF 파일로 로컬 디스크에 저장하는

Node.js/Express 서버를 만들어 보겠습니다.

종속성 설치

  1. 서버용 폴더 만들기:


    mkdir server
    cd server
    
  2. Node.js 프로젝트 초기화:


    npm init -y
    
  3. Expresscors 설치:

    npm install express cors
    

    설명

    • Express는 웹 서버 생성을 단순화합니다.
    • CORS(Cross-Origin Resource Sharing)는 Cross-Origin 요청을 허용하는 미들웨어입니다.
서버 코드 생성(index.js)

  1. 다음 코드를 사용하여 index.js 파일을 만듭니다.


    const express = require('express');
    const cors = require('cors');
    const fs = require('fs');
    const path = require('path');
    
    const app = express();
    const PORT = 3000;
    
    app.use(cors());
    app.use(express.json({ limit: '10mb' }));
    
    app.post('/upload', (req, res) => {
        const { image } = req.body;
    
        if (!image) {
            return res.status(400).json({ error: 'No image provided.' });
        }
    
        const buffer = Buffer.from(image, 'base64');
    
        // Save the image to disk
        const filename = `image_${Date.now()}.pdf`;
        const filepath = path.join(__dirname, 'uploads', filename);
    
        // Ensure the uploads directory exists
        if (!fs.existsSync('uploads')) {
            fs.mkdirSync('uploads');
        }
    
        fs.writeFile(filepath, buffer, (err) => {
            if (err) {
                console.error('Failed to save image:', err);
                return res.status(500).json({ error: 'Failed to save image.' });
            }
    
            console.log('Image saved:', filename);
            res.json({ message: 'Image uploaded successfully!', filename });
        });
    });
    
    // Start the server
    app.listen(PORT, () => {
        console.log(`Server is running on http://localhost:${PORT}`);
    });
    
  2. 웹 서버 실행:


    node index.js
    
Dynamsoft Document Viewer를 사용하여 PWA 문서 스캐너 구현

Dynamsoft Document Viewer를 시작하려면 GitHub 저장소(https://github.com/Dynamsoft/mobile-web-capture/tree/master/samples/complete-document-capturing-)에서 공식 샘플 코드를 다운로드하세요. 작업 흐름. 이 샘플은 Dynamsoft Document Viewer SDK를 사용하여 여러 이미지를 캡처하고 자르고 단일 문서로 결합하는 방법을 보여줍니다.

프로젝트를 기반으로 다음 기능을 추가합니다.

  • PWA를 지원합니다.
  • 스캔한 문서를 PDF 파일로 서버에 업로드하세요.

웹 프로젝트를 PWA와 호환되게 만들기

  1. PWA 프로젝트용 폴더 만들기:

    mkdir server
    cd server
    
  2. 샘플 코드를 클라이언트 폴더에 복사하세요.

  3. 다음 콘텐츠를 사용하여 프로젝트의 루트 디렉터리에 매니페스트.json 파일을 만듭니다.

    npm init -y
    
  4. 다음 콘텐츠로 프로젝트의 루트 디렉터리에 sw.js 파일을 만듭니다.

    npm install express cors
    
  5. index.html 파일에 서비스 워커를 등록하세요.

    const express = require('express');
    const cors = require('cors');
    const fs = require('fs');
    const path = require('path');
    
    const app = express();
    const PORT = 3000;
    
    app.use(cors());
    app.use(express.json({ limit: '10mb' }));
    
    app.post('/upload', (req, res) => {
        const { image } = req.body;
    
        if (!image) {
            return res.status(400).json({ error: 'No image provided.' });
        }
    
        const buffer = Buffer.from(image, 'base64');
    
        // Save the image to disk
        const filename = `image_${Date.now()}.pdf`;
        const filepath = path.join(__dirname, 'uploads', filename);
    
        // Ensure the uploads directory exists
        if (!fs.existsSync('uploads')) {
            fs.mkdirSync('uploads');
        }
    
        fs.writeFile(filepath, buffer, (err) => {
            if (err) {
                console.error('Failed to save image:', err);
                return res.status(500).json({ error: 'Failed to save image.' });
            }
    
            console.log('Image saved:', filename);
            res.json({ message: 'Image uploaded successfully!', filename });
        });
    });
    
    // Start the server
    app.listen(PORT, () => {
        console.log(`Server is running on http://localhost:${PORT}`);
    });
    

스캔한 문서를 PDF 파일로 업로드

  1. uiConfig.js에서 save라는 클릭 이벤트가 있는 사용자 정의 다운로드 버튼을 추가하세요.

    node index.js
    
  2. index.html에서 save 이벤트를 구현합니다. 문서를 PDF로 저장한 후 Blob을 Base64 문자열로 변환하고 서버에 업로드하세요.

    mkdir client
    cd client
    

PWA 문서 스캐너 실행

  1. 프로젝트의 루트 디렉터리에서 웹 서버를 시작합니다.

    {
        "short_name": "MyPWA",
        "name": "My Progressive Web App",
        "icons": [
            {
                "src": "icon.png",
                "sizes": "192x192",
                "type": "image/png"
            }
        ],
        "start_url": "/",
        "display": "standalone",
        "background_color": "#ffffff",
        "theme_color": "#000000"
    }
    
  2. 웹 브라우저에서 http://localhost:8000을 방문하세요.

    How to Build a PWA Document Scanner: Capture, Edit and Upload as PDF

소스 코드

https://github.com/yushulx/web-twain-document-scan-management/tree/main/examples/pwa

위 내용은 PWA 문서 스캐너를 구축하는 방법: PDF로 캡처, 편집 및 업로드의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.