The PyMuPDF4LLM API

property version

라이브러리의 버전을 출력합니다.

to_markdown(doc: pymupdf.Document | str, *, detect_bg_color: bool = True, dpi: int = 150, embed_images: bool = False, extract_words: bool = False, filename: str | None = None, fontsize_limit: float = 3, footer: bool = True, force_ocr: bool = False, force_text: bool = True, graphics_limit: int = None, hdr_info: Any = None, header: bool = True, ignore_alpha: bool = False, ignore_code: bool = False, ignore_graphics: bool = False, ignore_images: bool = False, image_format: str = 'png', image_path: str = '', image_size_limit: float = 0.05, margins: float | list = 0, ocr_dpi: int = 300, ocr_function: callable = None, ocr_language: str = 'eng', page_chunks: bool = False, page_height: float = None, page_separators: bool = False, page_width: float = 612, pages: list | range | None = None, show_progress: bool = False, table_strategy: str = 'lines_strict', use_glyphs: bool = False, use_ocr: bool = True, write_images: bool = False) str | list[dict]

파일의 페이지를 읽고 Markdown 형식으로 페이지 텍스트를 출력합니다. 세부 사항은 여러 매개변수로 제어할 수 있습니다. Markdown 텍스트에서 페이지 청크 구축 지원 이 지원됩니다.

매개변수:
  • doc (Document,str) – 파일 경로 문자열 또는 PyMuPDF Document (pymupdf.open 으로 생성)로 지정할 파일입니다. pathlib.Path 사양, Python 파일과 같은 객체, 메모리의 문서 등을 사용하려면 반드시 PyMuPDF Document 를 사용해야 합니다.

  • detect_bg_color (bool) – use_layout() must be False 페이지의 일반 배경색에 대한 간단한 확인을 수행합니다(기본값은 True). 이 색상을 가진 텍스트나 벡터는 무시됩니다. 감지 정확도를 높일 수 있습니다.

  • dpi (int) – 인치당 도트 수로 원하는 이미지 해상도를 지정합니다. write_images=True 또는 embed_images=True 인 경우에만 관련됩니다. 기본값은 150입니다.

  • embed_images (bool) – write_images 와 유사하지만 이미지가 base64 인코딩된 문자열로 마크다운 텍스트에 포함됩니다. write_images 와 상호 배타적이며 image_path 를 무시합니다. 마크다운 텍스트의 크기를 크게 증가시킬 수 있습니다.

  • extract_words (bool) – use_layout() must be False True 값은 page_chunks=True 를 강제하고 각 페이지 딕셔너리에 “words” 키를 추가합니다. 그 값은 PyMuPDFPage 메서드 get_text("words") 에서 제공하는 단어 목록입니다. 이 목록의 단어 순서는 추출된 텍스트와 동일합니다.

  • filename (str) – 작성된 이미지의 원하는 이미지 파일 이름을 덮어쓰거나 설정합니다. 문서가 메모리 객체로 제공되는 경우(고유한 파일 이름이 없음)에 유용합니다.

  • fontsize_limit (float) – use_layout() must be False 텍스트 추출을 위해 고려할 폰트 크기를 제한합니다. 폰트 크기가 설정된 값보다 작으면 텍스트가 추출 대상에서 제외됩니다. 기본값은 3 이며, 폰트 크기가 >= 3 인 텍스트만 추출 대상으로 고려됩니다.

  • footer (bool) – 페이지 푸터 콘텐츠를 켜거나 끄는 부울 값입니다. 이 매개변수는 모든 문서 페이지에서 푸터 텍스트를 포함할지 생략할지를 제어합니다. 문서에 반복적인 푸터 콘텐츠가 있어 전체 추출 데이터에 가치를 추가하지 않는 경우에 유용합니다. 기본값은 True 이며 푸터 콘텐츠가 고려됩니다.

  • force_ocr (bool) –

    if True, OCR will be applied to all pages regardless of their content.

    This may be useful for documents which are known to be image-based and thus profit from OCR, but which do not meet the default criteria for applying OCR. Default is False meaning that OCR will only be applied to pages which meet the default criteria.

    경고

    Requires that either one of the default supported OCR engines is installed or ocr_function specifies a callable OCR function. Otherwise, an exception will be raised.

  • force_text (bool) – 이미지/그래픽과 겹치는 경우에도 텍스트 출력을 생성합니다. 이 텍스트는 해당 이미지 뒤에 나타납니다.

  • graphics_limit (int) – use_layout() must be False 과도한 양의 벡터 그래픽 요소를 처리하는 것을 제한하는 데 사용합니다. 과학 문서나 그래픽 명령을 통해 텍스트를 시뮬레이션하는 페이지는 수만 개의 이러한 객체를 포함할 수 있습니다. 벡터 그래픽이 여러 목적으로 분석되므로 실행 시간이 빠르게 견딜 수 없게 될 수 있습니다. 이 매개변수를 사용하면 개수가 임계값을 초과하면 모든 벡터 그래픽이 무시됩니다.

  • hdr_infouse_layout() must be False 자체 헤더 감지 로직을 제공하려면 이것을 사용하세요. 이것은 호출 가능한 객체이거나 get_header_id 라는 메서드를 가진 객체일 수 있습니다. 텍스트 스팬(extractDICT() 에 포함된 스팬 딕셔너리)과 키워드 매개변수 “page”(소유 Page 객체)를 받아야 합니다. 빈 문자열 “” 또는 최대 6개의 “#” 문자 뒤에 공백 1개를 반환해야 합니다. 생략(None)하면 전체 문서 스캔을 수행하여 가장 인기 있는 폰트 크기를 찾고 이를 기반으로 헤더 수준을 파생합니다. 이 동작을 완전히 피하려면 hdr_info=lambda s, page=None: "" 또는 hdr_info=False 를 지정하세요.

  • header (bool) – 페이지 헤더 콘텐츠를 켜거나 끄는 부울 값입니다. 이 매개변수는 모든 문서 페이지에서 헤더 콘텐츠를 포함할지 생략할지를 제어합니다. 문서에 반복적인 헤더 콘텐츠가 있어 전체 추출 데이터에 가치를 추가하지 않는 경우에 유용합니다. 기본값은 True 이며 헤더 콘텐츠가 고려됩니다.

  • ignore_alpha (bool) – use_layout() must be False True 이면 완전히 투명한 경우에도 텍스트를 포함합니다. 기본값은 False 입니다: 투명한 텍스트는 무시되며 일반적으로 감지 정확도를 높입니다.

  • ignore_code (bool) – True 이면 고정 폭 텍스트 줄이 특별한 형식을 받지 않습니다. 코드 블록이 더 이상 생성되지 않습니다. extract_words=True 가 사용되면 이 값은 True 로 설정됩니다.

  • ignore_graphics (bool) – use_layout() must be False (v.0.0.20에서 새로 추가됨) 페이지의 벡터 그래픽을 무시합니다. 페이지가 매우 복잡할 때(프레젠테이션 슬라이드를 나타내는 문서에서 자주 발생) 텍스트를 올바르게 감지하는 데 도움이 될 수 있습니다. 또한 처리 시간을 단축합니다. 이것은 자동으로 테이블 감지를 방지합니다.

  • ignore_images (bool) – use_layout() must be False (v.0.0.20에서 새로 추가됨) 페이지의 이미지를 무시합니다. 페이지가 매우 복잡할 때(프레젠테이션 슬라이드를 나타내는 문서에서 자주 발생) 텍스트를 올바르게 감지하는 데 도움이 될 수 있습니다. 또한 처리 시간을 단축합니다.

  • image_format (str) – 확장자를 통해 원하는 이미지 형식을 지정합니다. 기본값은 “png”(portable network graphics)입니다. 다른 인기 있는 형식은 “jpg”일 수 있습니다. 가능한 값은 모든 지원되는 출력 형식 입니다.

  • image_path (str) – 이 폴더에 이미지를 저장합니다. write_images=True 인 경우 관련됩니다. 기본값은 스크립트 디렉토리의 경로입니다.

  • image_size_limit (float) – use_layout() must be False 이것은 0 <= value < 1 이어야 합니다. width / page.rect.width <= image_size_limit 또는 height / page.rect.height <= image_size_limit 이면 이미지가 무시됩니다. 예를 들어, 기본값 0.05는 포함을 고려하려면 이미지의 너비와 높이가 각각 페이지 너비와 높이의 5%보다 커야 함을 의미합니다.

  • margins (float,list) –

    use_layout() must be False 페이지 여백을 지정하는 float 또는 2개 또는 4개의 float 시퀀스. 여백 내부의 객체만 출력 대상으로 고려됩니다.

    • margin=f(left, top, right, bottom) 에 대해 (f, f, f, f) 를 생성합니다.

    • (top, bottom)(0, top, 0, bottom) 를 생성합니다.

    • 항상 전체 페이지를 읽으려면 (기본값), margins=0 을 사용하세요.

  • ocr_dpi (int) – specify the desired image resolution in dots per inch for applying OCR to the intermediate image of the page. Default value is 300. Only relevant if the page has been determined to profit from OCR (no or few text, most of the page covered by images or character-like vectors, etc.). Larger values do not usually increase the OCR precision. There also is a risk of over-sharpening the image which may decrease OCR precision. So the default value should probably be sufficiently high - in many cases you should see satisfactory results already with values of 150 or 200. Be aware that processing time and memory requirements grow quadratically with this value (an O(ocr_dpi²) impact).

  • ocr_function (callable) – if you want to provide your own OCR function, specify it here. If omitted (None), one of the available built-in OCR engines will be used.

  • ocr_language (str) – specify the language to be used by the Tesseract OCR engine. Default is “eng” (English). Make sure that the respective language data files are installed. Remember to use correct Tesseract language codes. Multiple languages can be specified by concatenating the respective codes with a plus sign “+”, for example “eng+deu” for English and German.

  • page_chunks (bool) –

    True 이면 출력은 Document.page_count 딕셔너리 목록(페이지당 하나)이 됩니다. 각 딕셔너리는 다음 구조를 가집니다:

    • ”metadata” - 문서의 메타데이터 Document.metadata 로 구성된 딕셔너리이며, 추가 키 “file_path” (파일 이름), “page_count” (문서의 페이지 수), “page_number” (1-기반 페이지 번호)로 보강됩니다.

    • ”toc_items” - 이 페이지를 가리키는 목차 항목 목록. 이 목록의 각 항목은 [lvl, title, pagenumber] 형식을 가지며, 여기서 lvl 은 계층 수준, title 은 문자열, pagenumber 는 1-기반 페이지 번호입니다.

    • ”tables” - Only if use_layout() is False a list of tables on this page. Each item is a dictionary with keys “bbox”, “row_count” and “col_count”. Key “bbox” is a pymupdf.Rect in tuple format of the table’s position on the page.

    • ”images” - Only if use_layout() is False 페이지의 이미지 목록. 이것은 페이지 메서드 Page.get_image_info() 의 복사본입니다.

    • ”graphics” - Only if use_layout() is False 페이지의 벡터 그래픽 사각형 목록. 이것은 메서드 Page.cluster_drawings() 에서 제공하는 클러스터링된 벡터 그래픽의 경계 상자 목록입니다.

    • ”text” - Markdown 텍스트로 된 페이지 콘텐츠.

    • ”words” - Only if use_layout() is False extract_words=True 가 사용된 경우. 이것은 page.get_text("words") 에서 제공하는 튜플 (x0, y0, x1, y1, "wordstring", bno, lno, wno) 목록입니다. 그러나 이러한 튜플의 순서 는 마크다운 텍스트 문자열에서 생성된 것과 동일하므로 다중 열 텍스트를 존중합니다. 테이블의 텍스트에도 적용됩니다: 단어는 테이블 행 셀의 순서로 추출됩니다.

    • ”text” - Markdown 텍스트로 된 페이지 콘텐츠.

    • ”page_boxes” - a list of dictionaries representing the layout boundary boxes. Each dictionary has the following structure:

      {
          "index": int,              # 0-based integer index of the box in reading sequence
          "class": str,              # one of "text", "picture", "table", etc.
          "bbox": [x0, y0, x1, y1],  # boundary box coordinates
          "pos": (start, stop),      # 0-based integers: bbox_text = chunk["text"][start:stop]
      }
      

      See: box classes

  • page_height (float) – 원하는 페이지 높이를 지정합니다. 관련성은 page_width 매개변수를 참조하세요. 기본값 None 을 사용하면 문서가 page_width 너비의 하나의 큰 페이지로 나타납니다. 결과적으로 이 경우 마크다운 페이지 구분자가 발생하지 않으며(마지막 것 제외), 각각 하나의 페이지 청크만 반환됩니다.

  • page_separators (bool) – True 이면 각 페이지 출력 끝에 문자열 --- end of page=n --- 를 삽입합니다. 디버깅 목적으로 사용됩니다. 페이지 번호는 0-기반입니다. 구분자 문자열은 줄바꿈으로 감싸집니다. 기본값은 False 입니다.

  • page_width (float) – 원하는 페이지 너비를 지정합니다. PDF, XPS 등 고정 페이지 너비를 가진 문서에서는 무시됩니다. 그러나 재배치 가능한 문서(예: 전자책, 오피스 [2] 또는 텍스트 파일)는 고정 페이지 크기가 없습니다. 기본적으로 Letter 형식 너비(612)와 무제한 페이지 높이를 가진 것으로 가정됩니다. 이것은 전체 문서가 하나의 큰 페이지로 처리됨 을 의미합니다.

  • pages (list) – 선택 사항, 출력을 위해 고려할 페이지(주의: 0-기반 페이지 번호 지정). 생략(None)하면 모든 페이지가 처리됩니다. 정수 항목이 있는 모든 Python 시퀀스가 허용됩니다. 시퀀스는 정렬되고 고유 항목만 포함하도록 처리됩니다.

  • show_progress (bool) – 기본값은 False 입니다. True 값은 페이지가 변환되는 동안 진행 표시줄을 표시합니다. tqdm 패키지가 설치되어 있으면 사용되고, 그렇지 않으면 내장 텍스트 기반 진행 표시줄이 사용됩니다.

  • table_strategy (str) – use_layout() must be False 참조: 테이블 감지 전략. 기본값은 배경색을 무시하는 "lines_strict" 입니다. 경우에 따라 다른 전략이 더 성공적일 수 있습니다. 예를 들어 모든 벡터 그래픽 객체를 감지에 사용하는 "lines" 입니다.

  • use_glyphs (bool) – use_layout() must be False (v.0.0.19에서 새로 추가됨) 기본값은 False 입니다. True 값은 폰트가 유니코드 값을 저장하지 않는 경우 문자 자체 대신 문자의 글리프 번호를 사용합니다.

  • use_ocr (bool) – use OCR capability to help analyse the page. This will OCR pages as determined by the default criteria.

  • write_images (bool) –

    이미지나 벡터 그래픽을 만나면 해당 페이지 영역에서 이미지가 생성되어 지정된 폴더에 저장됩니다. Markdown 참조가 이러한 이미지를 가리키도록 생성됩니다. 이러한 영역에 포함된 텍스트는 텍스트 출력에 포함되지 않습니다(이미지의 일부로 나타남). 따라서 예를 들어 문서에 전체 페이지 이미지에 텍스트가 작성된 경우 이 매개변수를 False 로 설정해야 합니다.

    PyMuPDF Layout 을 사용하는 경우 레이아웃 모듈에 의해 “picture”로 분류된 경계 상자는 이미지로 처리됩니다 - 덮고 있을 수 있는 텍스트, 이미지 또는 벡터 그래픽의 혼합과 무관합니다. force_text=True 가 사용되면 텍스트는 여전히 이러한 영역에서 추출되어 해당 이미지 참조 뒤에 출력에 포함됩니다.

반환:

선택된 모든 문서 페이지의 결합된 텍스트 문자열이거나 page_chunks=True 인 경우 딕셔너리 목록입니다.

to_text(doc: pymupdf.Document | str, *, **kwargs) str

Reads the pages of the file and outputs the text of its pages in plain text (TXT) format.

매개변수:
  • doc (Document,str) – 파일 경로 문자열 또는 PyMuPDF Document (pymupdf.open 으로 생성)로 지정할 파일입니다. pathlib.Path 사양, Python 파일과 같은 객체, 메모리의 문서 등을 사용하려면 반드시 PyMuPDF Document 를 사용해야 합니다.

  • use_ocr (bool) – 페이지 분석을 돕기 위해 OCR 기능 을 사용합니다.

  • ocr_language (str) – specify the language to be used by the Tesseract OCR engine. Default is “eng” (English). Make sure that the respective language data files are installed. Remember to use correct Tesseract language codes. Multiple languages can be specified by concatenating the respective codes with a plus sign “+”, for example “eng+deu” for English and German.

  • ocr_dpi (int) – 페이지의 중간 이미지에 OCR을 적용하기 위한 인치당 도트 수로 원하는 이미지 해상도를 지정합니다. 기본값은 400입니다. 페이지가 OCR로 이익을 얻을 것으로 판단된 경우(텍스트가 없거나 적고, 페이지 대부분이 이미지나 문자와 같은 벡터로 덮인 경우 등)에만 관련됩니다. 큰 값은 OCR 정밀도를 높일 수 있지만 메모리 요구 사항과 처리 시간을 증가시킵니다. 이미지를 과도하게 선명하게 만들어 OCR 정밀도를 떨어뜨릴 위험도 있습니다. 따라서 기본값은 충분히 높아야 합니다.

  • header (bool) – 페이지 헤더 콘텐츠를 켜거나 끄는 부울 값입니다. 이 매개변수는 모든 문서 페이지에서 헤더 콘텐츠를 포함할지 생략할지를 제어합니다. 문서에 반복적인 헤더 콘텐츠가 있어 전체 추출 데이터에 가치를 추가하지 않는 경우에 유용합니다. 기본값은 True 이며 헤더 콘텐츠가 작성됩니다.

  • footer (bool) – 페이지 푸터 콘텐츠를 켜거나 끄는 부울 값입니다. 이 매개변수는 모든 문서 페이지에서 푸터 콘텐츠를 포함할지 생략할지를 제어합니다. 문서에 반복적인 푸터 콘텐츠가 있어 전체 추출 데이터에 가치를 추가하지 않는 경우에 유용합니다. 기본값은 True 이며 푸터 콘텐츠가 작성됩니다.

  • ignore_code (bool) – True 이면 고정 폭 텍스트 줄이 특별한 형식을 받지 않습니다. 블록이 작성되지 않고 텍스트 줄이 연속적으로 작성됩니다.

  • pages (list) – 선택 사항, 출력을 위해 고려할 페이지(주의: 0-기반 페이지 번호 지정). 생략(None)하면 모든 페이지가 처리됩니다. 정수 항목이 있는 모든 Python 시퀀스가 허용됩니다. 시퀀스는 정렬되고 고유 항목만 포함하도록 처리됩니다.

  • force_text (bool) – 이미지/그래픽과 겹치는 경우에도 텍스트 출력을 생성합니다. 이 텍스트는 해당 이미지 참조 뒤에 나타납니다. 그러나 이미지(즉, “picture” 영역)는 텍스트 출력에 작성되지 않고 ==> picture [width x height] <== 와 같은 텍스트 줄로 출력에 나타납니다.

  • show_progress (bool) – 기본값은 False 입니다. True 값은 페이지가 변환되는 동안 진행 표시줄을 표시합니다. tqdm 패키지가 설치되어 있으면 사용되고, 그렇지 않으면 내장 텍스트 기반 진행 표시줄이 사용됩니다.

  • page_chunks (bool) –

    True 이면 출력은 Document.page_count 딕셔너리 목록(페이지당 하나)이 됩니다. 각 딕셔너리는 다음 구조를 가집니다:

    • ”metadata” - 문서의 메타데이터 Document.metadata 로 구성된 딕셔너리이며, 추가 키 “file_path” (파일 이름), “page_count” (문서의 페이지 수), “page_number” (1-기반 페이지 번호)로 보강됩니다.

    • ”toc_items” - 이 페이지를 가리키는 목차 항목 목록. 이 목록의 각 항목은 [lvl, title, pagenumber] 형식을 가지며, 여기서 lvl 은 계층 수준, title 은 문자열, pagenumber 는 1-기반 페이지 번호입니다.

    • ”tables” - empty list.

    • ”images” - empty list.

    • ”graphics” - empty list.

    • ”words” - empty list.

    • ”text” - page content as plain text.

    • ”page_boxes” - a list of dictionaries representing the layout boundary boxes. Each dictionary has the following structure:

      {
          "index": int,              # 0-based integer index of the box in reading sequence
          "class": str,              # one of "text", "picture", "table", etc.
          "bbox": [x0, y0, x1, y1],  # boundary box coordinates
          "pos": (start, stop),      # 0-based integers: bbox_text = chunk["text"][start:stop]
      }
      

      See: box classes

to_json(doc: pymupdf.Document | str, *, **kwargs) str

Parses the document and the specified pages and converts the result into a JSON formatted string.

매개변수:
  • doc (Document,str) – 파일 경로 문자열 또는 PyMuPDF Document (pymupdf.open 으로 생성)로 지정할 파일입니다. pathlib.Path 사양, Python 파일과 같은 객체, 메모리의 문서 등을 사용하려면 반드시 PyMuPDF Document 를 사용해야 합니다.

  • use_ocr (bool) – 페이지 분석을 돕기 위해 OCR 기능 을 사용합니다.

  • ocr_language (str) – specify the language to be used by the Tesseract OCR engine. Default is “eng” (English). Make sure that the respective language data files are installed. Remember to use correct Tesseract language codes. Multiple languages can be specified by concatenating the respective codes with a plus sign “+”, for example “eng+deu” for English and German.

  • ocr_dpi (int) – 페이지의 중간 이미지에 OCR을 적용하기 위한 인치당 도트 수로 원하는 이미지 해상도를 지정합니다. 기본값은 400입니다. 페이지가 OCR로 이익을 얻을 것으로 판단된 경우(텍스트가 없거나 적고, 페이지 대부분이 이미지나 문자와 같은 벡터로 덮인 경우 등)에만 관련됩니다. 큰 값은 OCR 정밀도를 높일 수 있지만 메모리 요구 사항과 처리 시간을 증가시킵니다. 이미지를 과도하게 선명하게 만들어 OCR 정밀도를 떨어뜨릴 위험도 있습니다. 따라서 기본값은 충분히 높아야 합니다.

  • image_dpi (int) – 인치당 도트 수로 원하는 이미지 해상도를 지정합니다. 기본값은 150입니다. write_images=True 또는 embed_images=True 매개변수 중 하나가 사용된 경우에만 관련됩니다.

  • image_format (str) – 확장자를 통해 원하는 이미지 형식을 지정합니다. 기본값은 “png”(portable network graphics)입니다. 다른 인기 있는 형식은 “jpg”일 수 있습니다. 가능한 값은 모든 지원되는 출력 형식 입니다. write_images=True 또는 embed_images=True 매개변수 중 하나가 사용된 경우에만 관련됩니다.

  • image_path (str) – 이 폴더에 이미지를 저장합니다. write_images=True 인 경우 관련됩니다. 기본값은 스크립트 디렉토리의 경로입니다. “picture”로 분류된 페이지 영역은 지정된 위치에 이미지 파일로 작성됩니다. 이미지 파일 이름은 {image_path}/{filename}-pagenumber-image_number.{image_format} 형식입니다.

  • force_text (bool) – 레이아웃 모듈에 의해 “picture”로 분류된 영역에 작성된 텍스트에 대한 텍스트 출력을 생성합니다. 그림 콘텐츠가 저장되지 않은 경우 특히 유용할 수 있습니다.

  • show_progress (bool) – 처리 중 진행 표시줄을 표시합니다.

  • embed_images (bool) – “picture” 경계 상자에 대한 이미지 바이너리를 저장합니다. Base64 인코딩된 이미지가 JSON 출력에 포함됩니다. 사용된 경우 image_path 를 무시합니다. 이것은 JSON 텍스트의 크기를 크게 증가시킬 수 있습니다.

  • write_images (bool) – store image files “picture” boundary boxes. When encountering images, image files will be created from the respective page area and stored in the specified folder. Any text contained in these areas will still be included in the text output.

  • pages (list) – 선택 사항, 출력을 위해 고려할 페이지(주의: 0-기반 페이지 번호 지정). 생략(None)하면 모든 페이지가 처리됩니다. 0page_count - 1 사이의 정수를 포함하는 유효한 Python 시퀀스를 지정하세요.

반환 형식:

str

See JSON Schema for the structure of the output JSON string.

참고

About box classes

If page_chunks = True the return objects for to_markdown & to_text contains a list of dictionaries representing the layout boundary boxes page_boxes, within that a key class indicates the type of box content therein.

The return object for to_json contains a similar key called boxclass.

The possible string values are for this class / boxclass key are:

text
picture
table
caption
title
section-header
page-header
page-footer
list-item
footnote
formula
use_layout(yes: bool = True)

Switch on/off the use of the PyMuPDF Layout module.

If yes=True (default), the layout module will be used for page analysis for optimal results. If yes=False, the layout module will not be used.

get_key_values(doc: pymupdf.Document | str) list[dict]

Parse the document if it is a Form PDF and extract key-value pairs from all form fields (widgets).

Please note that this method is only relevant for PDF documents that contain widgets. Otherwise, an empty list will be returned.

The function is always available – independently of whether you are using the PyMuPDF Layout module or not.

Each dictionary item has the following structure:

{
    "field_name": str,      # the full name of the form field, components separated by dots
    {
        "value": str,       # the field value as string
        "pages": list,      # list of 0-based page numbers where the field appears
    }
}
markdown_to_pdf(md_path: str | pathlib.Path, user_css: str | None = None, page_rect: rect-like | None = None, margins: rect-like | None) = None, archive: str | pathlib.Path | None = None, output_path: str | pathlib.Path | None = None) pymupdf.Document | None

Convert the markdown text content of the file specified by md_path into a PDF document.

The function is always available – independently of whether you are using the PyMuPDF Layout module or not.

매개변수:
  • md_path (str|Path) – the file path of the markdown file to be converted.

  • user_css (str|None) – optional, a string of CSS code to be applied to the markdown content. This may be used to customize the appearance of the generated PDF document. If None (default), the built-in default CSS is used.

  • page_rect (rect-like|None) – optional, the rectangle defining the page boundaries for the generated PDF document. If None (default), ISO A4 page dimensions are used. To use one of PyMuPDF’s predefined page formats, use e.g. pymupdf.paper_rect("Letter").

  • margins (rect-like|None) – optional, the margins (borders) for the generated pages. This must be a sequence of four floats [left, top, right, bottom] specifying the respective border width in points (1/72 inches). If None (default), the default [50, 50, 50, 50] margins are used.

  • archive (str|Archive|None) – optional. This is be required if the markdown source references images that are not stored in the same folder as the markdown file. In this case, Archive (아카이브) must be a pymupdf.Archive object which provides access to the respective image files. If None (default), it is assumed that all referenced images are stored in the same folder as the markdown file. The parameter may also be required if a custom user_css references external resources like font files.

  • output_path (str|Path|None) – optional, the file path where the generated PDF document will be saved. If specified, the generated PDF will be saved to that location. If None (default), the document is returned as a pymupdf.Document object.

참고

PyMuPDF Layout 사용에 대한 추가 배경 정보 및 개선 사항의 현재 상태는 이 사이트 를 참조하세요.

LlamaMarkdownReader(*args, **kwargs)

LlamaIndex 패키지를 사용하여 pdf_markdown_reader.PDFMarkdownReader 를 생성합니다. 이 패키지는 pymupdf4llm 설치 시 자동으로 설치되지 않습니다.

가능한 인수에 대한 자세한 내용은 LlamaIndex 문서 [1] 를 참조하세요.

발생:

NotImplementedError: 필요한 LlamaIndex 패키지를 설치하세요.

반환:

pdf_markdown_reader.PDFMarkdownReader 를 생성하고 “Successfully imported LlamaIndex” 메시지를 발행합니다. 이 메서드는 실행하는 데 몇 초가 필요합니다. 마크다운 리더 사용에 대한 자세한 내용은 아래를 참조하세요.


class IdentifyHeaders

참고

Only if use_layout() is False

__init__(self, doc: pymupdf.Document | str, *, pages: list | range | None = None, body_limit: float = 11, max_levels: int = 6)

텍스트 폰트 크기를 마크다운 구문에서 헤더 레벨을 나타내는 데 사용되는 ‘#’ 문자 수에 매핑하는 객체를 생성합니다. 이 객체는 문서에서 폰트 크기 “인기도”를 스캔하여 생성됩니다. 가장 인기 있는 폰트 크기와 모든 작은 크기는 본문 텍스트에 사용됩니다. 더 큰 폰트 크기는 해당 헤더 레벨에 매핑됩니다 - 이는 HTML 태그 <h1> 에서 <h6> 에 해당합니다.

모든 폰트 크기는 정수 값으로 반올림됩니다.

6개 이상의 헤더 레벨이 필요한 경우, <h6> 폰트 크기보다 작은 가장 큰 숫자가 본문 텍스트에 사용됩니다.

객체를 생성하면 문서 전체의 텍스트를 읽고 검사합니다 - 이후 to_markdown() 메서드에서 문서를 다시 읽는 것과는 무관하게. to_markdown() 메서드는 기본적으로 hdr_info=None 매개변수를 재정의하지 않으면 이 객체를 생성합니다.

매개변수:
  • doc (Document,str) – 파일 경로 문자열 또는 pymupdf.open 을 통해 생성된 PyMuPDF Document로 지정할 파일입니다. pathlib.Path 사양, Python 파일과 같은 객체, 메모리의 문서 등을 사용하려면 반드시 PyMuPDF Document를 사용해야 합니다.

  • pages (list) – 선택 사항, 고려할 페이지. 생략하면 모든 페이지가 처리됩니다.

  • body_limit (float) – 본문 텍스트의 기본 폰트 크기 제한. 문서 스캔이 유효한 정보를 제공하지 않을 때만 사용됩니다.

  • max_levels (int) – 사용할 최대 헤더 레벨 수. 유효한 값은 range(1, 7) 입니다. 기본값은 6이며, 이는 HTML 태그 <h1> 에서 <h6> 에 해당합니다. 더 작은 값은 생성되는 헤더 레벨 수를 제한합니다. 예를 들어, 값 3은 헤더 태그 “#”, “##”, “###”만 생성합니다. 본문 텍스트는 “###”에 해당하는 폰트 크기보다 작은 모든 폰트 크기에 대해 가정됩니다.

get_header_id(self, span: dict, page=None) str

적절한 마크다운 헤더 접두사를 반환합니다. 이는 빈 문자열이거나 공백이 뒤따르는 “#” 문자열입니다.

“dict” 추출에서 텍스트 스팬이 주어지면, 0에서 n까지 연결된 ‘#’ 문자의 마크다운 헤더 접두사 문자열을 결정합니다.

매개변수:
  • span (dict) – page.get_text("dict") 에 의해 반환되는 것과 동일한 텍스트 스팬 정보를 포함하는 딕셔너리입니다.

  • page (Page) – 소유 페이지 객체. 추가 정보가 추출되어야 할 때 사용할 수 있습니다.

반환:

공백이 뒤따르는 “#” 문자열입니다.

header_id

정수 폰트 크기를 {14: '# ', 12: '## '} 와 같은 마크다운 헤더 문자열에 매핑하는 딕셔너리입니다. 이 딕셔너리는 IdentifyHeaders 생성자에 의해 생성됩니다. 키는 문서의 텍스트 스팬 폰트 크기입니다. 값은 해당 헤더 문자열입니다.

body_limit

본문 텍스트의 폰트 크기 제한을 나타내는 정수 값. 이는 min(header_id.keys()) - 1 로 계산됩니다. 위 예시에서 body_limit은 11이 됩니다.


헤더 레벨 제한 방법 (예제)

생성된 헤더 레벨을 3으로 제한:

import pymupdf, pymupdf4llm

filename = "input.pdf"
doc = pymupdf.open(filename)  # use a Document for subsequent processing
my_headers = pymupdf4llm.IdentifyHeaders(doc, max_levels=3)  # generate header info
md_text = pymupdf4llm.to_markdown(doc, hdr_info=my_headers)

자체 헤더 로직 제공 방법 (예제 1)

사전 결정된 고정 폰트 크기를 사용하는 자체 함수 제공:

import pymupdf, pymupdf4llm

filename = "input.pdf"
doc = pymupdf.open(filename)  # use a Document for subsequent processing

def my_headers(span, page=None):
    """
    Provide some custom header logic.
    This is a callable which accepts a text span and the page.
    Could be extended to check for other properties of the span, for
    instance the font name, text color and other attributes.
    """
    # header level is h1 if font size is larger than 14
    # header level is h2 if font size is larger than 10
    # otherwise it is body text
    if span["size"] > 14:
        return "# "
    elif span["size"] > 10:
        return "## "
    else:
        return ""

# this will *NOT* scan the document for font sizes!
md_text = pymupdf4llm.to_markdown(doc, hdr_info=my_headers)

자체 헤더 로직 제공 방법 (예제 2)

이 사용자 함수는 문서의 목차를 사용합니다 – 북마크 텍스트가 페이지의 헤더 줄로도 존재한다는 가정 하에(반드시 그럴 필요는 없습니다!):

import pymupdf, pymupdf4llm

filename = "input.pdf"
doc = pymupdf.open(filename)  # use a Document for subsequent processing
TOC = doc.get_toc()  # use the table of contents for determining headers

def my_headers(span, page=None):
    """
    Provide some custom header logic (experimental!).
    This callable checks whether the span text matches any of the
    TOC titles on this page.
    If so, use TOC hierarchy level as header level.
    """
    # TOC items on this page:
    toc = [t for t in TOC if t[-1] == page.number + 1]

    if not toc:  # no TOC items on this page
        return ""

    # look for a match in the TOC items
    for lvl, title, _ in toc:
        if span["text"].startswith(title):
            return "#" * lvl + " "
        if title.startswith(span["text"]):
            return "#" * lvl + " "

    return ""

# this will *NOT* scan the document for font sizes!
md_text = pymupdf4llm.to_markdown(doc, hdr_info=my_headers)

class TocHeaders

참고

Only if use_layout() is False

__init__(self, doc: pymupdf.Document | str)

문서의 목차(TOC)를 사용하여 헤더 레벨을 결정하는 객체를 생성합니다. 객체 생성 시 Document.get_toc() 메서드를 통해 목차를 읽습니다. TOC 데이터는 to_markdown() 메서드에서 헤더 레벨을 결정하는 데 사용됩니다.

이것은 IdentifyHeaders 의 대안입니다. 전체 문서를 통해 폰트 크기를 식별하는 대신, 문서의 목차(TOC)를 사용하여 페이지의 헤더를 식별합니다. IdentifyHeaders 와 마찬가지로, 이것도 헤더를 찾는 것을 보장하지는 않지만, 잘 구성된 목차의 경우 폰트 크기 기반 접근 방식보다 문서 페이지의 헤더 줄을 더 정확하게 식별할 가능성이 높습니다.

또한 전체 문서 스캔을 실행하거나 문서 페이지에 액세스하지 않으므로 폰트 크기 기반 접근 방식보다 훨씬 빠르다는 장점이 있습니다.

이 접근 방식이 매우 잘 작동하는 예는 Adobe의 PDF 문서 파일입니다.

이 기능은 목차가 일반 표준 텍스트로 존재할 수 있는 문서 페이지를 읽지 않습니다. Document.get_toc() 메서드에서 제공하는 데이터에만 액세스합니다. 목차가 북마크 모음으로 제공되지 않는 문서의 헤더는 식별하지 않습니다.

get_header_id(self, span: dict, page=None) str

적절한 마크다운 헤더 접두사를 반환합니다. 이는 빈 문자열이거나 공백이 뒤따르는 “#” 문자열입니다.

“dict” 추출 변형에서 텍스트 스팬이 주어지면, 0에서 n까지 연결된 “#” 문자의 마크다운 헤더 접두사 문자열을 결정합니다.

매개변수:
  • span (dict) – page.get_text("dict") 에 의해 반환되는 것과 동일한 텍스트 스팬 정보를 포함하는 딕셔너리입니다.

  • page (Page) – 소유 페이지 객체. 추가 정보가 추출되어야 할 때 사용할 수 있습니다.

반환:

공백이 뒤따르는 “#” 문자열입니다.

TocHeaders 클래스 사용 방법

이것은 헤더 식별을 위해 TocHeaders 를 사용하는 이전 예제 2 의 버전입니다:

import pymupdf, pymupdf4llm

filename = "input.pdf"

doc = pymupdf.open(filename)  # use a Document for subsequent processing
my_headers = pymupdf4llm.TocHeaders(doc)  # use the table of contents for determining headers

# this will *NOT* scan the document for font sizes!
md_text = pymupdf4llm.to_markdown(doc, hdr_info=my_headers)

class pdf_markdown_reader.PDFMarkdownReader
load_data(file_path: Path | str, extra_info: Dict | None = None, **load_kwargs: Any) List[LlamaIndexDocument]

이것은 현재 마크다운 데이터를 추출하는 데 사용해야 하는 마크다운 리더의 유일한 메서드입니다. 어떤 경우에도 aload_data()lazy_load_data() 메서드를 무시하세요. use_doc_meta() 와 같은 다른 메서드는 의미가 있을 수도 있고 없을 수도 있습니다. 자세한 내용은 LlamaIndex 문서 [1] 를 참조하세요.

내부적으로 메서드는 to_markdown() 을 실행합니다.

반환:

LlamaIndexDocument 문서 목록 - 페이지당 하나씩.


For a list of changes, please see file CHANGES.md.

각주

This software is provided AS-IS with no warranty, either express or implied. This software is distributed under license and may not be copied, modified or distributed except as expressly authorized under the terms of that license. Refer to licensing information at artifex.com or contact Artifex Software Inc., 39 Mesa Street, Suite 108A, San Francisco CA 94129, United States for further information.

/* this script is used to adjust the search widget and to add line breaks after parameters in the signature blocks for better readability */