패키지, 저장소 및 앱 카테고리 검색

패키지 상세v1.3.2

html2md

HTML을 마크다운으로 변환하기 위한 라이브러리입니다. CommonMark, 간단한 테이블 및 사용자 정의 변환 규칙을 지원합니다.

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
7.8만
좋아요
63
Pub 점수
140

패키지 설치

flutter pub add html2md

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

HTML 콘텐츠를 마크다운 형식으로 변환하는 플러터/다트 패키지로, CommonMark 표준, 기본 테이블 렌더링 및 사용자 정의 변환 규칙을 지원합니다. 콘텐츠 에디터, 문서 도구, 블로그 플랫폼 등과 같이 풍부한 HTML 텍스트를 깔끔하고 읽기 쉬운 마크다운으로 변환해야 하는 애플리케이션에 적합합니다. 이 라이브러리는 Android, iOS, 웹, macOS, Windows, Linux 등 모든 주요 플랫폼에서 호환되며, 크로스플랫폼 개발에 매우 유연합니다. 확장성 덕분에 특정 사용 사례에 맞는 사용자 정의 파싱 로직을 정의할 수 있습니다.

사용 사례

  • HTML 이메일을 마크다운으로 변환하기
  • HTML 소스에서 블로그 게시물 렌더링하기
  • Markdown 출력을 사용하여 콘텐츠 편집기 만들기
  • 사용자 생성 HTML을 구조화된 마크다운으로 변환

주요 기능

  • CommonMark 사양을 지원합니다
  • 간단한 테이블을 처리합니다
  • 사용자 정의 변환 규칙
  • 크로스 플랫폼 호환성
  • 경량이며 통합이 쉬움

적합한 대상

  • 콘텐츠 관리 시스템
  • 문서 생성기
  • 마크다운 기반의 메모 앱
  • 사용자로부터 제출된 HTML을 처리하는 앱

고려 사항

  • 복잡한 HTML 구조에 대한 제한된 지원
  • 사용자 정의 규칙은 추가 구현이 필요합니다
  • 모든 HTML 스타일 속성을 유지하지 않을 수 있습니다
  • 매우 큰 HTML 문서에 최적화되지 않음

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

English | 简体中文

html2md

Pub Build status

A library for converting HTML to Markdown in Dart. It supports CommonMark, simple table and custom converting rules.

Usage

A simple usage example:

import 'package:html2md/html2md.dart' as html2md;

main() {
    var html = '<h1>HTML2MD Demo</h1>';
    print(html2md.convert(html));
}

In flutter, you can use the flutter_markdown for rendering:

import 'package:html2md/html2md.dart' as html2md;
import 'package:flutter_markdown/flutter_markdown.dart';

build(BuildContext context) {
    // Caution!
    // This is not best practice, you should not call convert in build
    // and the converted markdown should put in state.
    var html = '<h1>HTML2MD Demo</h1>';
    var markdown = html2md.convert(html);
    return Markdown(data: markdown);
}

Config

You can config convert style by passing styleOptions to convert, elements that should be ignored also can be set with ignore. If you want to customize element converting, use custom rules!

html2md.convert(html,
    styleOptions: {'headingStyle': 'atx'},
    ignore: ['script'],
    rules: [Rule('custom')]);

The default and available style options:

Name Default Options
headingStyle "setext" "setext", "atx"
hr "* * *" "* * *", "- - -", "_ _ _"
bulletListMarker "*" "*", "-", "_"
codeBlockStyle "indented" "indented", "fenced"
fence "```" "```", "~~~"
emDelimiter "_" "_", "*"
strongDelimiter "**" "**", "__"
linkStyle "inlined" "inlined", "referenced"
linkReferenceStyle "full" "full", "collapsed", "shortcut"

Table support

Basic table converting is supported!

Html table source:

<table>
    <tr>
        <th>First Header</th>
        <th>First Header</th> 
    </tr>
    <tr>
        <td>Content Cell</td>
        <td>Content Cell</td>
    </tr>
    <tr>
        <td>Content Cell</td>
        <td>Content Cell</td>
    </tr>
</table>

The converted markdown source:

| First Header  | Second Header |
| ----- | ----- |
| Content Cell  | Content Cell  |
| Content Cell  | Content Cell  |

The converted markdown table:

First Header Second Header
Content Cell Content Cell
Content Cell Content Cell

Custom Rules

Want to customize element converting? Write your rules!

Rule fields explaination

final String name; // unique rule name
final List<String>? filters; // simple element name filters, e.g. ['aside']
final FilterFn? filterFn; // function for building complex element filter logic
final Replacement? replacement; // function for doing the replacing
final Append? append; // function for appending content

Rule example - Convert the onebox section of discourse post to a link

<aside class="onebox">
  <header class="source">
      <img src="https://discoursesite/uploads/default/original/1X/test.png" class="site-icon" width="32" height="32">
      <a href="https://events.google.com/io/program/content?4=topic_flutter&amp;lng=zh-CN" target="_blank" rel="noopener">Google I/O 2021</a>
  </header>
</aside>
Rule(
  'discourse-onebox',
  filterFn: (node) {
    // Find aside with onebox class
    if (node.nodeName == 'aside' &&
        node.className.contains('onebox')) {
        return true;
    }
    return false;
  },
  replacement: (content, node) {
    // find the first a element under header
    var header = node.firstChild;
    var link = header!
        .childNodes()
        .firstWhere((element) => element.nodeName == 'a');
    var href = link.getAttribute('href');
    if (href != null && href.isNotEmpty) {
      return '[$href]($href)'; // build the link
    }
    return '';
  },
)

Test

dart run test

Features and bugs

Please file feature requests and bugs at the issue tracker.

Inspiration

html2md is basicly a simplify version of Node's turndown

License

Created from templates made available by Stagehand under a BSD-style license.

카테고리

의존성

의존성 목록 2 개

소스 저장소

이 패키지를 사용하는 프로젝트