java使用pandoc將markdown轉換為word文件

大綱

pandoc 下載和基本使用

java 操作pandoc 批次轉換為word文件

使用screw生成資料庫文件

場景概述

在專案開發時,平時喜歡用markdown寫文件,但專案交付的時候,需要轉換為更加正式的word文件進行交付。 現在考慮用pandoc將。md檔案轉換為word文件,文件目錄結構如下:

dev-docs|__docs|____docsify |____imgs 文件圖片存放|____core |____other _sidebar。md md文件目錄

pandoc 下載和基本使用

官網下載pandoc: https://www。pandoc。org/installing。html

Pandoc 可以用於各種文件格式之間的轉換。如: Markdown、Microsoft Word、HTML、EPUB、roff man、LaTeX、PDF。

命令列使用示例: https://www。pandoc。org/demos。html

// 1 。md 檔案轉換為word文件pandoc test。md -o newtest。docx// 2 多個md轉換為一個word文件,pandoc xx1。md xx2。md -o 合併後的。docx /**3 自定義文件格模板格式**///3。1 首先獲取pandoc 自帶的doc模板文件muban。docxpandoc。exe -o muban。docx ——print-default-data-file=reference。docx//3。2 開啟muban。docx,修改模板檔案中樣式(如下圖,需要透過右鍵修改樣式方式,模板才能生效)//3。3 使用模板文件,進行轉換pandoc。exe xx1。md xx2。md -o 合併後的。docx ——reference-doc=C:\\reference。docx

修改調整後的模板文件 muban。docx 「連結」

java使用pandoc將markdown轉換為word文件

需要透過右鍵修改樣式方式,模板才能生效

markdown轉word樣式沒處理好,生成word後新建樣式手動處理

java使用pandoc將markdown轉換為word文件

透過名稱可以控制樣式排序

java使用pandoc將markdown轉換為word文件

段落背景色設定

java使用pandoc將markdown轉換為word文件

前後縮排控制

java 操作pandoc 批次轉換為word文件

效果圖預覽:

java使用pandoc將markdown轉換為word文件

markdown文件

java使用pandoc將markdown轉換為word文件

轉換後word效果圖

程式碼如下

/** * 透過pandoc輸出預設模板到custom。docx: pandoc。exe -o custom。docx ——print-default-data-file=reference。docx *

* 使用指定的檔案作為輸出檔案的格式參考。參考檔案的內容被忽略,只使用其中的樣式和文件屬性(包括邊界、頁面尺寸、頁首頁尾等) (——reference-doc=File(custom。docx)) 指定要生成的word模板 */public class Markdown2Docx_backup { //pandoc。exe 檔案絕對路徑 private static final String PANDOC_PATH = “C:\\doc\\pandoc。exe ”; //markdown文件(。md字尾格式) 所在路徑 private static final String DOCS_DIR = “C:\\doc\\docs\\docs”; //文件依賴圖片路徑 private static final String IMG_DIR = “C:\\doc\\docs\\docs\\imgs”; //側邊欄_sidebar。md,根據側邊欄順序轉換文件 private static final String _sidebar = “C:\\doc\\docs\\docs\\_sidebar。md”; //docx模板 使用 pandoc 進行文件轉換(markdown轉word) http://t。zoukankan。com/kofyou-p-14932700。html private static final String reference_docx = “C:\\doc\\docs\\docs\\reference。docx”; public static void main(String[] args) { copyImageDir(); String mdFilePath = buildAllMdFilePath(); convertmd2Docx(mdFilePath); } /** * 解析側邊欄 _sidebar。md 生成所有markdown檔案路徑,如: xx1。md xx2。md *

* 側邊欄內容示例: -[文件說明](/job-debug。md) */ private static final String buildAllMdFilePath() { StringBuilder mds = new StringBuilder(); File sidebarFile = new File(_sidebar); if (!sidebarFile。exists()) { System。err。println(“_sidebar。md 側邊欄檔案不存在”); return null; } //獲取檔案首行作為檔名 List contents = FileUtil。readTxtFile(_sidebar, “utf-8”); for (String content : contents) { //content示例必須有()將md路徑包含: -[文件說明](/job-debug。md) try { if (StringUtil。isNullOrEmpty(content。trim())) { continue; } if (content。indexOf(“](”) < 0) { System。out。println(content + “, 不是markdown 路徑不進行轉換”); continue; } //解析出 /job-debug。md String mdPath = content。split(“]\\(”)[1]。replace(“)”, “”)。replace(“/”, “\\”)。trim(); if (mdPath。endsWith(“。md”)) { mds。append(DOCS_DIR)。append(“\\”)。append(mdPath)。append(“ ”); } else { mds。append(DOCS_DIR)。append(“\\”)。append(mdPath)。append(“。md”)。append(“ ”); } } catch (Exception e) { System。err。println(“從文件中解析md檔案路徑失敗”); } } return mds。toString(); } private static void convertmd2Docx(String mdFilePath) { String docxPath = DOCS_DIR + “\\開發手冊。docx”; Runtime rn = Runtime。getRuntime(); try { //pandoc xx1。md xx2。md -o test。docx String command; File mubanDoc = new File(reference_docx); if (mubanDoc。exists()) { System。out。println(“使用docx模板進行文件轉換: ” + reference_docx); command = PANDOC_PATH + “ ” + mdFilePath + “ -o ” + docxPath + “ ——toc-depth=3 ——reference-doc=” + reference_docx; } else { //pandoc xx1。md xx2。md -o test。docx command = PANDOC_PATH + “ ” + mdFilePath + “ -o ” + docxPath + “ ”; } System。out。println(command); Process exec = rn。exec(command); } catch (Exception e) { System。out。println(“呼叫服務生成word文件錯誤 ” + e。getMessage()); } } /** * 1 (pandoc test。md -o test。docx 無法識別。。/imgs ),將。。/imgs替換為/imgs絕對路徑 *

* 2 修改 markdown文件中的圖片引入方式,手動將文件中所有。。/imgs 替換為/imgs ![業務用例圖](/imgs/complex-email。png) *

* 3 透過copyImageDir()方法,將/docs/imgs目錄下的圖片,複製到當前程式執行的根目錄/的imgs下(/imgs) */ private static void copyImageDir() { //文件中依賴圖片檔案路徑 File docImgsDir = new File(IMG_DIR); //解決pandoc 轉換檔案時,找不到圖片路徑。。/imgs問題 File dir = new File(“/imgs”); if (!dir。exists()) { dir。mkdir(); File[] files = docImgsDir。listFiles(); for (File file : files) { String s = FileUtil。readToString(file); try { FileUtil。writeToFile(dir + “\\” + file。getName(), s, “utf-8”, false); } catch (IOException e) { e。printStackTrace(); } } System。out。println(“複製文件圖片到路徑:” + dir。getAbsolutePath()); } else { System。out。println(“文件圖片已存在路徑:” + dir。getAbsolutePath()); } }}

參考文件

Pandoc使用技巧: https://blog。csdn。net/weixin_39617497/article/details/117897721

pandoc使用latex模板轉pdf檔案: https://blog。51cto。com/u_1472521/5202317

使用 pandoc 進行文件轉換(markdown轉word) http://t。zoukankan。com/kofyou-p-14932700。html

使用screw生成資料庫文件

文件地址: 「連結」 https://gitee。com/leshalv/screw

生成文件示例

java使用pandoc將markdown轉換為word文件

自動生成文件目錄

java使用pandoc將markdown轉換為word文件

資料表和欄位描述示例

引入screw依賴

<!——文件地址 ——><!——資料庫文件生成工具 screw——> org。freemarker freemarker 2。3。30 cn。smallbun。screw screw-core 1。0。3

編碼實現生成文件

/** * 資料庫 文件生成器, 普通 main 方法生成方式 * 參考文件 https://gitee。com/leshalv/screw */public class DocGen1 { public static final String db_users = “monitor,mgr”; public static final String db_pwds = “1,1”; public static void main(String[] args) { DocGen1 gen1 = new DocGen1(); String[] users = db_users。split(“,”);//迴圈生成多個使用者 String[] pwds = db_pwds。split(“,”); for (int i = 0; i < users。length; i++) { gen1。docGeneration(hikariConfig(users[i], pwds[i])); } } interface Config { EngineFileType engineFileType = EngineFileType。HTML; String docDesc = “資料庫表說明文件 ”; String version = DateUtils。UTC_TIME_ZONE。getDisplayName(); } private static HikariConfig hikariConfig(String db_user, String pwd) { HikariConfig hikariConfig = new HikariConfig();//資料來源// hikariConfig。setDriverClassName(“oracle。jdbc。driver。OracleDriver”); hikariConfig。setDriverClassName(“com。mysql。cj。jdbc。Driver”); hikariConfig。setJdbcUrl(“jdbc:mysql:。0。0。1:3306/database”); hikariConfig。setUsername(db_user); hikariConfig。setPassword(pwd); hikariConfig。addDataSourceProperty(“useInformationSchema”, “true”); hikariConfig。setMinimumIdle(2); hikariConfig。setMaximumPoolSize(5); return hikariConfig; } /** * 文件生成 */ void docGeneration(HikariConfig hikariConfig) { DataSource dataSource = new HikariDataSource(hikariConfig); EngineConfig engineConfig = EngineConfig。builder() 。fileOutputDir(DocGeneratorApplication。OUTPUT_DIR)//生成檔案路徑 。openOutputDir(true)//開啟目錄 。fileType(Config。engineFileType)//檔案型別 。produceType(EngineTemplateType。freemarker)//生成模板實現 。build(); ArrayList ignoreTableName = new ArrayList<>();//忽略表 ignoreTableName。add(“test_user”); ArrayList ignorePrefix = new ArrayList<>(); ignorePrefix。add(“test_”); ignorePrefix。add(“bak_”); ArrayList ignoreSuffix = new ArrayList<>();//忽略表字首 ignoreSuffix。add(“_001”); ignoreSuffix。add(“_009”); ignoreSuffix。add(“_copy”); ProcessConfig processConfig = ProcessConfig。builder() 。designatedTableName(new ArrayList<>())//指定生成邏輯 。designatedTablePrefix(new ArrayList<>())//根據名稱指定表生成 。designatedTableSuffix(new ArrayList<>())//根據表字首生成 。ignoreTableName(ignoreTableName)//根據表字尾生成 。ignoreTablePrefix(ignorePrefix)//忽略表名 。ignoreTableSuffix(ignoreSuffix)。build();//忽略表字首 Configuration config = Configuration。builder()//忽略表字尾 。version(Config。version)//配置 。description(Config。docDesc + hikariConfig。getUsername())//版本 。dataSource(dataSource)//描述 。engineConfig(engineConfig)//資料來源 。produceConfig(processConfig)。title(hikariConfig。getUsername())//生成配置 。build(); new DocumentationExecute(config)。execute();//生成配置 }}

頂部