IT박스

Android 앱에서 PDF를 작성하는 방법은 무엇입니까?

itboxs 2020. 6. 17. 19:22
반응형

Android 앱에서 PDF를 작성하는 방법은 무엇입니까? [닫은]


Android 애플리케이션에서 PDF 파일을 작성하는 방법이 있습니까?


누구나 Android 기기에서 PDF를 생성하려면 다음과 같이하십시오.


API 레벨 19 이상의 디바이스를 개발중인 경우 내장 PrintedPdfDocument를 사용할 수 있습니다. http://developer.android.com/reference/android/print/pdf/PrintedPdfDocument.html

// open a new document
PrintedPdfDocument document = new PrintedPdfDocument(context,
     printAttributes);

// start a page
Page page = document.startPage(0);

// draw something on the page
View content = getContentView();
content.draw(page.getCanvas());

// finish the page
document.finishPage(page);
. . .
// add more pages
. . .
// write the document content
document.writeTo(getOutputStream());

//close the document
document.close();

복잡한 기능으로 PDF를 작성하는 요령은 원하는 XML 레이아웃으로 더미 활동을하는 것입니다. 그런 다음이 더미 활동을 열고 프로그래밍 방식 으로 스크린 샷 을 찍고이 라이브러리를 사용하여 해당 이미지를 pdf로 변환 할 수 있습니다 . 물론 두 페이지 이상 스크롤 할 수없는 것과 같은 제한 사항이 있지만 제한된 응용 프로그램의 경우 빠르고 쉽습니다. 이것이 누군가를 돕기를 바랍니다!


안드로이드에서 영어가 아닌 문자로 임의의 HTML을 PDF로 변환하는 문제에 대한 완전한 해결책을 찾는 것은 쉽지 않습니다. 러시아어 유니 코드 문자로 테스트합니다.

우리는 세 개의 라이브러리를 사용합니다 :

(1) HTML에서 XHTML 로의 변환을위한 Jsoup (jsoup-1.7.3.jar)

(2) iTextPDF (itextpdf-5.5.0.jar),

(3) XMLWorker (xmlworker-5.5.1.jar).

public boolean createPDF(String rawHTML, String fileName, ContextWrapper context){
    final String APPLICATION_PACKAGE_NAME = context.getBaseContext().getPackageName();
    File path = new File( Environment.getExternalStorageDirectory(), APPLICATION_PACKAGE_NAME );
    if ( !path.exists() ){ path.mkdir(); }
    File file = new File(path, fileName);

    try{

    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
    document.open();

    // Подготавливаем HTML
    String htmlText = Jsoup.clean( rawHTML, Whitelist.relaxed() );
    InputStream inputStream = new ByteArrayInputStream( htmlText.getBytes() );

    // Печатаем документ PDF
    XMLWorkerHelper.getInstance().parseXHtml(writer, document,
        inputStream, null, Charset.defaultCharset(), new MyFont());

    document.close();
    return true;

    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return false;
    } catch (DocumentException e) {
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } 

어려운 문제는 iTextPDF XMLWorker 라이브러리를 사용하여 러시아어 문자를 PDF로 표시하는 것입니다. 이를 위해 자체 FontProvider 인터페이스 구현을 만들어야합니다.

public class MyFont implements FontProvider{
    private static final String FONT_PATH = "/system/fonts/DroidSans.ttf";
    private static final String FONT_ALIAS = "my_font";

    public MyFont(){ FontFactory.register(FONT_PATH, FONT_ALIAS); }

    @Override
    public Font getFont(String fontname, String encoding, boolean embedded,
        float size, int style, BaseColor color){

        return FontFactory.getFont(FONT_ALIAS, BaseFont.IDENTITY_H, 
            BaseFont.EMBEDDED, size, style, color);
    }

    @Override
    public boolean isRegistered(String name) { return name.equals( FONT_ALIAS ); }
}

여기에서는 시스템 폴더에있는 표준 Android 글꼴 Droid Sans를 사용합니다.

private static final String FONT_PATH = "/system/fonts/DroidSans.ttf";

조금 늦었고 아직 직접 테스트하지는 않았지만 BSD 라이센스 가 적용 되는 다른 라이브러리 Android PDF Writer 입니다.

업데이트 라이브러리를 직접 시도했습니다. 간단한 pdf 생성 (텍스트, 선, 사각형, 비트 맵, 글꼴을 추가하는 방법을 제공)과 함께 작동합니다. 유일한 문제는 생성 된 PDF가 메모리의 문자열에 저장되어 큰 문서에서 메모리 문제가 발생할 수 있다는 것입니다.


PDFJet offers an open-source version of their library that should be able to handle any basic PDF generation task. It's a purely Java-based solution and it is stated to be compatible with Android. There is a commercial version with some additional features that does not appear to be too expensive.


Late, but relevant to request and hopefully helpful. If using an external service (as suggested in the reply by CommonsWare) then Docmosis has a cloud service that might help - offloading processing to a cloud service that does the heavy processing. That approach is ideal in some circumstances but of course relies on being net-connected.


U can also use PoDoFo library. The main goal is that it published under LGPL. Since it is written in C++ you should cross-compile it using NDK and write C-side and Java wrapper. Some of third-party libraries can be used from OpenCV project. Also in OpenCV project U can find android.toolchain.cmake file, which will help you with generating Makefile.

참고URL : https://stackoverflow.com/questions/2499960/how-to-create-pdfs-in-an-android-app

반응형