├── .gitignore ├── .header.json ├── .header.txt ├── LICENSE ├── README.md ├── docx_renderer.go ├── go.mod ├── go.sum ├── main.go ├── sample.docx └── sample.md /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, built with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | 14 | # Dependency directories (remove the comment below to include it) 15 | # vendor/ 16 | 17 | # https://github.com/88250/header 18 | header 19 | header.exe 20 | 21 | .idea 22 | -------------------------------------------------------------------------------- /.header.json: -------------------------------------------------------------------------------- 1 | { 2 | "Dir": ".", 3 | "Template": ".header.txt", 4 | "Includes": [ 5 | "*.go" 6 | ], 7 | "Excludes": ["html/**"], 8 | "UseDefaultExcludes": true, 9 | "Properties": { 10 | "Year": "2020-present", 11 | "Owner": "b3log.org" 12 | } 13 | } -------------------------------------------------------------------------------- /.header.txt: -------------------------------------------------------------------------------- 1 | Lute DOCX - 一款将 Markdown 文本转换为 Word 文档 (.docx) 的小工具 2 | Copyright (c) {{.Year}}, {{.Owner}} 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU Affero General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU Affero General Public License for more details. 13 | 14 | You should have received a copy of the GNU Affero General Public License 15 | along with this program. If not, see . -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published by 637 | the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## 💡 简介 2 | 3 | Lute DOCX 是一款将 Markdown 文本转换为 Word 文档 (.docx) 的小工具。通过 [Lute](https://github.com/88250/lute) 解析 Markdown 然后再通过 [unioffice](https://github.com/unidoc/unioffice) 生成 DOCX。 4 | 5 | ## ✨ 特性 6 | 7 | * 几乎支持所有 Markdown 语法元素 8 | * 图片会通过地址自动拉取并渲染 9 | * 支持封面配置 10 | 11 | ## 📸 截图 12 | 13 | ![sample](https://user-images.githubusercontent.com/873584/79592318-69a17100-810c-11ea-8c26-a6168e681325.png) 14 | 15 | ## ⚗ 用法 16 | 17 | 命令行参数说明: 18 | 19 | * `--mdPath`:待转换的 Markdown 文件路径 20 | * `--savePath`:转换后 DOCX 的保存路径 21 | * `--coverTitle`:封面 - 标题 22 | * `--coverAuthor`:封面 - 作者 23 | * `--coverAuthorLink`:封面 - 作者链接 24 | * `--coverLink`:封面 - 原文链接 25 | * `--coverSource`:封面 - 来源网站 26 | * `--coverSourceLink`:封面 - 来源网站链接 27 | * `--coverLicense`:封面 - 文档许可协议 28 | * `--coverLicenseLink`:封面 - 文档许可协议链接 29 | * `--coverLogoLink`:封面 - 图标链接 30 | * `--coverLogoTitle`:封面 - 图标标题 31 | * `--coverLogoTitleLink`:封面 - 图标标题链接 32 | 33 | ## 🐛 已知问题 34 | 35 | * 没有代码高亮,代码块统一使用绿色渲染 36 | * 没有渲染 Emoji 37 | * 表格没有边框 38 | * 表格单元格折行计算有问题 39 | * 粗体、斜体需要字体本身支持 40 | 41 | ## 🏘️ 社区 42 | 43 | * [讨论区](https://ld246.com/tag/lute) 44 | * [报告问题](https://github.com/88250/lute-docx/issues/new) 45 | * 欢迎关注 B3log 开源社区微信公众号 `B3log开源` 46 | ![b3logos.png](https://b3logfile.com/file/2019/10/image-d3c00d78.png) 47 | 48 | ## 📄 开源协议 49 | 50 | Lute DOCX 使用 [AGPLv3](https://www.gnu.org/licenses/agpl-3.0.txt) 开源协议。 51 | 52 | ## 🙏 鸣谢 53 | 54 | * [对中文语境优化的 Markdown 引擎 Lute](https://ld246.com/article/1567047822949) 55 | * [Go 实现的 Office 文档操作工具库](https://github.com/unidoc/unioffice) 56 | -------------------------------------------------------------------------------- /docx_renderer.go: -------------------------------------------------------------------------------- 1 | // Lute DOCX - 一款将 Markdown 文本转换为 Word 文档 (.docx) 的小工具 2 | // Copyright (c) 2020-present, b3log.org 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Affero General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Affero General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Affero General Public License 15 | // along with this program. If not, see . 16 | 17 | package main 18 | 19 | import ( 20 | "fmt" 21 | "image" 22 | "io/ioutil" 23 | "math" 24 | "net/http" 25 | "net/url" 26 | "os" 27 | "strconv" 28 | "strings" 29 | "time" 30 | 31 | "github.com/88250/lute/ast" 32 | "github.com/88250/lute/lex" 33 | "github.com/88250/lute/parse" 34 | "github.com/88250/lute/render" 35 | "github.com/88250/lute/util" 36 | "github.com/unidoc/unioffice/color" 37 | "github.com/unidoc/unioffice/common" 38 | "github.com/unidoc/unioffice/document" 39 | "github.com/unidoc/unioffice/measurement" 40 | "github.com/unidoc/unioffice/schema/soo/wml" 41 | ) 42 | 43 | // DocxRenderer 描述了 DOCX 渲染器。 44 | type DocxRenderer struct { 45 | *render.BaseRenderer 46 | needRenderFootnotesDef bool 47 | 48 | Cover *DocxCover // 封面 49 | 50 | doc *document.Document // DOCX 生成器句柄 51 | zoom float64 // 字体、行高大小倍数 52 | fontSize int // 字体大小 53 | lineHeight float64 // 行高 54 | heading1Size float64 // 一级标题大小 55 | heading2Size float64 // 二级标题大小 56 | heading3Size float64 // 三级标题大小 57 | heading4Size float64 // 四级标题大小 58 | heading5Size float64 // 五级标题大小 59 | heading6Size float64 // 六级标题大小 60 | margin float64 // 页边距 61 | paragraphs []*document.Paragraph // 当前段落栈 62 | runs []*document.Run // 当前排版栈 63 | images []string // 生成图片后待清理的临时文件路径 64 | } 65 | 66 | // DocxCover 描述了 DOCX 封面。 67 | type DocxCover struct { 68 | Title string // 标题 69 | AuthorLabel string // 作者: 70 | Author string // 作者 71 | AuthorLink string // 作者链接 72 | LinkLabel string // 原文链接: 73 | Link string // 原文链接 74 | SourceLabel string // 来源网站: 75 | Source string // 来源网站 76 | SourceLink string // 来源网站链接 77 | LicenseLabel string // 许可协议: 78 | License string // 许可协议 79 | LicenseLink string // 许可协议链接 80 | LogoLink string // 图标链接 81 | LogoTitle string // 图片标题 82 | LogoTitleLink string // 图标标题链接 83 | } 84 | 85 | func (r *DocxRenderer) RenderCover() { 86 | para := r.doc.AddParagraph() 87 | run := para.AddRun() 88 | run.AddBreak() 89 | run.AddBreak() 90 | run.AddBreak() 91 | run.AddBreak() 92 | run.AddBreak() 93 | run.AddBreak() 94 | run.AddBreak() 95 | run.AddBreak() 96 | run.AddBreak() 97 | run.AddBreak() 98 | logoImgPath, ok, isTemp := r.downloadImg(r.Cover.LogoLink) 99 | if ok { 100 | img, _ := common.ImageFromFile(logoImgPath) 101 | imgRef, _ := r.doc.AddImage(img) 102 | para.Properties().SetAlignment(wml.ST_JcCenter) 103 | inline, _ := run.AddDrawingInline(imgRef) 104 | width, height := r.getImgSize(logoImgPath) 105 | inline.SetSize(measurement.Distance(width), measurement.Distance(height)) 106 | 107 | if isTemp { 108 | r.images = append(r.images, logoImgPath) 109 | } 110 | } 111 | 112 | run.AddBreak() 113 | run.AddBreak() 114 | run.AddText(r.Cover.LogoTitle) 115 | run.AddBreak() 116 | run.AddBreak() 117 | 118 | run = para.AddRun() 119 | run.Properties().SetSize(28) 120 | run.AddText(r.Cover.Title) 121 | run.AddBreak() 122 | run.AddBreak() 123 | run.AddBreak() 124 | 125 | para = r.doc.AddParagraph() 126 | run = para.AddRun() 127 | run.Properties().SetSize(12) 128 | run.AddText(r.Cover.AuthorLabel) 129 | link := para.AddHyperLink() 130 | link.SetTarget(r.Cover.AuthorLink) 131 | run = link.AddRun() 132 | run.Properties().SetStyle("Hyperlink") 133 | run.AddText(r.Cover.Author) 134 | run.AddBreak() 135 | 136 | run = para.AddRun() 137 | run.Properties().SetSize(12) 138 | run.AddText(r.Cover.LinkLabel) 139 | link = para.AddHyperLink() 140 | link.SetTarget(r.Cover.Link) 141 | run = link.AddRun() 142 | run.Properties().SetStyle("Hyperlink") 143 | run.AddText(r.Cover.Link) 144 | run.AddBreak() 145 | 146 | run = para.AddRun() 147 | run.Properties().SetSize(12) 148 | run.AddText(r.Cover.SourceLabel) 149 | link = para.AddHyperLink() 150 | link.SetTarget(r.Cover.Source) 151 | run = link.AddRun() 152 | run.Properties().SetStyle("Hyperlink") 153 | run.AddText(r.Cover.Source) 154 | run.AddBreak() 155 | 156 | run = para.AddRun() 157 | run.Properties().SetSize(12) 158 | run.AddText(r.Cover.LicenseLabel) 159 | link = para.AddHyperLink() 160 | link.SetTarget(r.Cover.LicenseLink) 161 | run = link.AddRun() 162 | run.Properties().SetStyle("Hyperlink") 163 | run.AddText(r.Cover.License) 164 | run.AddBreak() 165 | 166 | footer := r.doc.AddFooter() 167 | para = footer.AddParagraph() 168 | para.Properties().SetAlignment(wml.ST_JcRight) 169 | run = para.AddRun() 170 | run.Properties().SetSize(8) 171 | run.AddText(r.Cover.LinkLabel) 172 | link = para.AddHyperLink() 173 | link.SetTarget(r.Cover.Link) 174 | run = link.AddRun() 175 | run.Properties().SetStyle("Hyperlink") 176 | run.AddText(r.Cover.Link) 177 | 178 | para = r.doc.AddParagraph() 179 | section := para.Properties().AddSection(wml.ST_SectionMarkContinuous) 180 | section.SetFooter(footer, wml.ST_HdrFtrDefault) 181 | } 182 | 183 | // NewDocxRenderer 创建一个 HTML 渲染器。 184 | func NewDocxRenderer(tree *parse.Tree, options *render.Options) *DocxRenderer { 185 | doc := document.New() 186 | linkStyle := doc.Styles.AddStyle("Hyperlink", wml.ST_StyleTypeCharacter, false) 187 | linkStyle.SetName("Hyperlink") 188 | linkStyle.SetBasedOn("DefaultParagraphFont") 189 | linkColor := color.FromHex("#4285F4") 190 | linkStyle.RunProperties().Color().SetColor(linkColor) 191 | linkStyle.RunProperties().SetUnderline(wml.ST_UnderlineSingle, linkColor) 192 | 193 | codeStyle := doc.Styles.AddStyle("Code", wml.ST_StyleTypeCharacter, false) 194 | codeStyle.SetName("Code") 195 | codeStyle.SetBasedOn("DefaultParagraphFont") 196 | codeColor := color.FromHex("#FF9933") 197 | codeStyle.RunProperties().Color().SetColor(codeColor) 198 | codeStyle.RunProperties().SetUnderline(wml.ST_UnderlineSingle, codeColor) 199 | 200 | codeBlockStyle := doc.Styles.AddStyle("CodeBlock", wml.ST_StyleTypeCharacter, false) 201 | codeBlockStyle.SetName("Code") 202 | codeBlockStyle.SetBasedOn("DefaultParagraphFont") 203 | codeBlockColor := color.FromHex("#569E3D") 204 | codeBlockStyle.RunProperties().Color().SetColor(codeBlockColor) 205 | codeBlockStyle.RunProperties().SetUnderline(wml.ST_UnderlineSingle, codeBlockColor) 206 | 207 | ret := &DocxRenderer{BaseRenderer: render.NewBaseRenderer(tree, options), needRenderFootnotesDef: false, doc: doc} 208 | ret.zoom = 0.8 209 | ret.fontSize = int(math.Floor(14 * ret.zoom)) 210 | ret.lineHeight = 24.0 * ret.zoom 211 | ret.heading1Size = 24 * ret.zoom 212 | ret.heading2Size = 22 * ret.zoom 213 | ret.heading3Size = 20 * ret.zoom 214 | ret.heading4Size = 18 * ret.zoom 215 | ret.heading5Size = 16 * ret.zoom 216 | ret.heading6Size = 14 * ret.zoom 217 | ret.margin = 60 * ret.zoom 218 | 219 | ret.RendererFuncs[ast.NodeDocument] = ret.renderDocument 220 | ret.RendererFuncs[ast.NodeParagraph] = ret.renderParagraph 221 | ret.RendererFuncs[ast.NodeText] = ret.renderText 222 | ret.RendererFuncs[ast.NodeCodeSpan] = ret.renderCodeSpan 223 | ret.RendererFuncs[ast.NodeCodeSpanOpenMarker] = ret.renderCodeSpanOpenMarker 224 | ret.RendererFuncs[ast.NodeCodeSpanContent] = ret.renderCodeSpanContent 225 | ret.RendererFuncs[ast.NodeCodeSpanCloseMarker] = ret.renderCodeSpanCloseMarker 226 | ret.RendererFuncs[ast.NodeCodeBlock] = ret.renderCodeBlock 227 | ret.RendererFuncs[ast.NodeCodeBlockFenceOpenMarker] = ret.renderCodeBlockOpenMarker 228 | ret.RendererFuncs[ast.NodeCodeBlockFenceInfoMarker] = ret.renderCodeBlockInfoMarker 229 | ret.RendererFuncs[ast.NodeCodeBlockCode] = ret.renderCodeBlockCode 230 | ret.RendererFuncs[ast.NodeCodeBlockFenceCloseMarker] = ret.renderCodeBlockCloseMarker 231 | ret.RendererFuncs[ast.NodeMathBlock] = ret.renderMathBlock 232 | ret.RendererFuncs[ast.NodeMathBlockOpenMarker] = ret.renderMathBlockOpenMarker 233 | ret.RendererFuncs[ast.NodeMathBlockContent] = ret.renderMathBlockContent 234 | ret.RendererFuncs[ast.NodeMathBlockCloseMarker] = ret.renderMathBlockCloseMarker 235 | ret.RendererFuncs[ast.NodeInlineMath] = ret.renderInlineMath 236 | ret.RendererFuncs[ast.NodeInlineMathOpenMarker] = ret.renderInlineMathOpenMarker 237 | ret.RendererFuncs[ast.NodeInlineMathContent] = ret.renderInlineMathContent 238 | ret.RendererFuncs[ast.NodeInlineMathCloseMarker] = ret.renderInlineMathCloseMarker 239 | ret.RendererFuncs[ast.NodeEmphasis] = ret.renderEmphasis 240 | ret.RendererFuncs[ast.NodeEmA6kOpenMarker] = ret.renderEmAsteriskOpenMarker 241 | ret.RendererFuncs[ast.NodeEmA6kCloseMarker] = ret.renderEmAsteriskCloseMarker 242 | ret.RendererFuncs[ast.NodeEmU8eOpenMarker] = ret.renderEmUnderscoreOpenMarker 243 | ret.RendererFuncs[ast.NodeEmU8eCloseMarker] = ret.renderEmUnderscoreCloseMarker 244 | ret.RendererFuncs[ast.NodeStrong] = ret.renderStrong 245 | ret.RendererFuncs[ast.NodeStrongA6kOpenMarker] = ret.renderStrongA6kOpenMarker 246 | ret.RendererFuncs[ast.NodeStrongA6kCloseMarker] = ret.renderStrongA6kCloseMarker 247 | ret.RendererFuncs[ast.NodeStrongU8eOpenMarker] = ret.renderStrongU8eOpenMarker 248 | ret.RendererFuncs[ast.NodeStrongU8eCloseMarker] = ret.renderStrongU8eCloseMarker 249 | ret.RendererFuncs[ast.NodeBlockquote] = ret.renderBlockquote 250 | ret.RendererFuncs[ast.NodeBlockquoteMarker] = ret.renderBlockquoteMarker 251 | ret.RendererFuncs[ast.NodeHeading] = ret.renderHeading 252 | ret.RendererFuncs[ast.NodeHeadingC8hMarker] = ret.renderHeadingC8hMarker 253 | ret.RendererFuncs[ast.NodeList] = ret.renderList 254 | ret.RendererFuncs[ast.NodeListItem] = ret.renderListItem 255 | ret.RendererFuncs[ast.NodeThematicBreak] = ret.renderThematicBreak 256 | ret.RendererFuncs[ast.NodeHardBreak] = ret.renderHardBreak 257 | ret.RendererFuncs[ast.NodeSoftBreak] = ret.renderSoftBreak 258 | ret.RendererFuncs[ast.NodeHTMLBlock] = ret.renderHTML 259 | ret.RendererFuncs[ast.NodeInlineHTML] = ret.renderInlineHTML 260 | ret.RendererFuncs[ast.NodeLink] = ret.renderLink 261 | ret.RendererFuncs[ast.NodeImage] = ret.renderImage 262 | ret.RendererFuncs[ast.NodeBang] = ret.renderBang 263 | ret.RendererFuncs[ast.NodeOpenBracket] = ret.renderOpenBracket 264 | ret.RendererFuncs[ast.NodeCloseBracket] = ret.renderCloseBracket 265 | ret.RendererFuncs[ast.NodeOpenParen] = ret.renderOpenParen 266 | ret.RendererFuncs[ast.NodeCloseParen] = ret.renderCloseParen 267 | ret.RendererFuncs[ast.NodeLinkText] = ret.renderLinkText 268 | ret.RendererFuncs[ast.NodeLinkSpace] = ret.renderLinkSpace 269 | ret.RendererFuncs[ast.NodeLinkDest] = ret.renderLinkDest 270 | ret.RendererFuncs[ast.NodeLinkTitle] = ret.renderLinkTitle 271 | ret.RendererFuncs[ast.NodeStrikethrough] = ret.renderStrikethrough 272 | ret.RendererFuncs[ast.NodeStrikethrough1OpenMarker] = ret.renderStrikethrough1OpenMarker 273 | ret.RendererFuncs[ast.NodeStrikethrough1CloseMarker] = ret.renderStrikethrough1CloseMarker 274 | ret.RendererFuncs[ast.NodeStrikethrough2OpenMarker] = ret.renderStrikethrough2OpenMarker 275 | ret.RendererFuncs[ast.NodeStrikethrough2CloseMarker] = ret.renderStrikethrough2CloseMarker 276 | ret.RendererFuncs[ast.NodeTaskListItemMarker] = ret.renderTaskListItemMarker 277 | ret.RendererFuncs[ast.NodeTable] = ret.renderTable 278 | ret.RendererFuncs[ast.NodeTableHead] = ret.renderTableHead 279 | ret.RendererFuncs[ast.NodeTableRow] = ret.renderTableRow 280 | ret.RendererFuncs[ast.NodeTableCell] = ret.renderTableCell 281 | ret.RendererFuncs[ast.NodeEmoji] = ret.renderEmoji 282 | ret.RendererFuncs[ast.NodeEmojiUnicode] = ret.renderEmojiUnicode 283 | ret.RendererFuncs[ast.NodeEmojiImg] = ret.renderEmojiImg 284 | ret.RendererFuncs[ast.NodeEmojiAlias] = ret.renderEmojiAlias 285 | ret.RendererFuncs[ast.NodeFootnotesDef] = ret.renderFootnotesDef 286 | ret.RendererFuncs[ast.NodeFootnotesRef] = ret.renderFootnotesRef 287 | ret.RendererFuncs[ast.NodeToC] = ret.renderToC 288 | ret.RendererFuncs[ast.NodeBackslash] = ret.renderBackslash 289 | ret.RendererFuncs[ast.NodeBackslashContent] = ret.renderBackslashContent 290 | return ret 291 | } 292 | 293 | func (r *DocxRenderer) Render() (output []byte) { 294 | r.LastOut = lex.ItemNewline 295 | 296 | ast.Walk(r.Tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus { 297 | extRender := r.ExtRendererFuncs[n.Type] 298 | if nil != extRender { 299 | output, status := extRender(n, entering) 300 | r.WriteString(output) 301 | return status 302 | } 303 | 304 | render := r.RendererFuncs[n.Type] 305 | if nil == render { 306 | if nil != r.DefaultRendererFunc { 307 | return r.DefaultRendererFunc(n, entering) 308 | } else { 309 | return r.renderDefault(n, entering) 310 | } 311 | } 312 | return render(n, entering) 313 | }) 314 | 315 | if 0 < len(r.FootnotesDefs) { 316 | output = r.RenderFootnotesDefs(r.Tree.Context) 317 | } 318 | return 319 | } 320 | 321 | func (r *DocxRenderer) renderDefault(n *ast.Node, entering bool) ast.WalkStatus { 322 | if entering { 323 | r.WriteString("not found render function for node [type=" + n.Type.String() + ", Tokens=" + util.BytesToStr(n.Tokens) + "]") 324 | } 325 | return ast.WalkContinue 326 | } 327 | 328 | func (r *DocxRenderer) renderBackslashContent(node *ast.Node, entering bool) ast.WalkStatus { 329 | if entering { 330 | r.Write(node.Tokens) 331 | } 332 | return ast.WalkContinue 333 | } 334 | 335 | func (r *DocxRenderer) renderBackslash(node *ast.Node, entering bool) ast.WalkStatus { 336 | return ast.WalkContinue 337 | } 338 | 339 | func (r *DocxRenderer) renderToC(node *ast.Node, entering bool) ast.WalkStatus { 340 | if entering { 341 | headings := r.headings() 342 | length := len(headings) 343 | if 1 > length { 344 | return ast.WalkContinue 345 | } 346 | r.WriteString("
") 347 | for i, heading := range headings { 348 | level := strconv.Itoa(heading.HeadingLevel) 349 | spaces := (heading.HeadingLevel - 1) * 2 350 | r.WriteString(strings.Repeat(" ", spaces)) 351 | r.WriteString("") 352 | r.WriteString("" + heading.Text() + "
") 353 | } 354 | r.WriteString("
\n\n") 355 | } 356 | return ast.WalkContinue 357 | } 358 | 359 | func (r *DocxRenderer) headings() (ret []*ast.Node) { 360 | for n := r.Tree.Root.FirstChild; nil != n; n = n.Next { 361 | r.headings0(n, &ret) 362 | } 363 | return 364 | } 365 | 366 | func (r *DocxRenderer) headings0(n *ast.Node, headings *[]*ast.Node) { 367 | if ast.NodeHeading == n.Type { 368 | *headings = append(*headings, n) 369 | return 370 | } 371 | if ast.NodeList == n.Type || ast.NodeListItem == n.Type || ast.NodeBlockquote == n.Type { 372 | for c := n.FirstChild; nil != c; c = c.Next { 373 | r.headings0(c, headings) 374 | } 375 | } 376 | } 377 | 378 | func (r *DocxRenderer) RenderFootnotesDefs(context *parse.Context) []byte { 379 | //if r.needRenderFootnotesDef { 380 | // return nil 381 | //} 382 | // 383 | //r.addPage() 384 | //r.renderThematicBreak(nil, false) 385 | //for i, def := range context.FootnotesDefs { 386 | // r.pdf.SetAnchor(string(def.Tokens)) 387 | // r.WriteString(fmt.Sprint(i+1) + ". ") 388 | // tree := &parse.Tree{Name: "", Context: context} 389 | // tree.Context.Tree = tree 390 | // tree.Root = &ast.Node{Type: ast.NodeDocument} 391 | // tree.Root.AppendChild(def) 392 | // r.Tree = tree 393 | // r.needRenderFootnotesDef = true 394 | // r.Render() 395 | // r.Newline() 396 | //} 397 | //r.needRenderFootnotesDef = false 398 | //r.renderFooter() 399 | return nil 400 | } 401 | 402 | func (r *DocxRenderer) renderFootnotesRef(node *ast.Node, entering bool) ast.WalkStatus { 403 | //x := r.pdf.GetX() + 1 404 | //r.pdf.SetX(x) 405 | //y := r.pdf.GetY() 406 | //r.pdf.SetFont("regular", "R", 8) 407 | //r.pdf.SetTextColor(66, 133, 244) 408 | // 409 | //idx := string(node.Tokens) 410 | //width, _ := r.pdf.MeasureTextWidth(idx[1:]) 411 | //r.pdf.SetY(y - 4) 412 | //r.pdf.Cell(nil, idx[1:]) 413 | //r.pdf.AddInternalLink(idx, x-3, y-9, width+4, r.lineHeight) 414 | // 415 | //x += width 416 | //r.pdf.SetX(x) 417 | //r.pdf.SetY(y) 418 | //font := r.peekFont() 419 | //r.pdf.SetFont(font.family, font.style, font.size) 420 | //textColor := r.peekTextColor() 421 | //r.pdf.SetTextColor(textColor.R, textColor.G, textColor.B) 422 | return ast.WalkContinue 423 | } 424 | 425 | func (r *DocxRenderer) renderFootnotesDef(node *ast.Node, entering bool) ast.WalkStatus { 426 | if !r.needRenderFootnotesDef { 427 | return ast.WalkContinue 428 | } 429 | return ast.WalkContinue 430 | } 431 | 432 | func (r *DocxRenderer) renderCodeBlock(node *ast.Node, entering bool) ast.WalkStatus { 433 | if entering { 434 | if !node.IsFencedCodeBlock { 435 | // 缩进代码块处理 436 | r.renderCodeBlockLike(node.Tokens) 437 | return ast.WalkContinue 438 | } 439 | } 440 | return ast.WalkContinue 441 | } 442 | 443 | // renderCodeBlockCode 进行代码块 HTML 渲染,实现语法高亮。 444 | func (r *DocxRenderer) renderCodeBlockCode(node *ast.Node, entering bool) ast.WalkStatus { 445 | if entering { 446 | r.renderCodeBlockLike(node.Tokens) 447 | } 448 | return ast.WalkContinue 449 | } 450 | 451 | func (r *DocxRenderer) renderCodeBlockLike(content []byte) { 452 | para := r.doc.AddParagraph() 453 | r.pushPara(¶) 454 | run := para.AddRun() 455 | run.Properties().SetStyle("CodeBlock") 456 | r.pushRun(&run) 457 | r.WriteString(util.BytesToStr(content)) 458 | run.AddBreak() 459 | r.popRun() 460 | r.reRun() 461 | r.popPara() 462 | } 463 | 464 | func (r *DocxRenderer) renderCodeSpanLike(content []byte) { 465 | para := r.peekPara() 466 | run := para.AddRun() 467 | run.Properties().SetStyle("Code") 468 | r.pushRun(&run) 469 | r.WriteString(util.BytesToStr(content)) 470 | r.popRun() 471 | r.reRun() 472 | } 473 | 474 | func (r *DocxRenderer) reRun() { 475 | if nil != r.peekRun() { 476 | // 如果链接之前有输出的话需要先结束掉,然后重新开一个 477 | r.popRun() 478 | para := r.peekPara() 479 | run := para.AddRun() 480 | r.pushRun(&run) 481 | } 482 | } 483 | 484 | func (r *DocxRenderer) renderCodeBlockCloseMarker(node *ast.Node, entering bool) ast.WalkStatus { 485 | return ast.WalkContinue 486 | } 487 | 488 | func (r *DocxRenderer) renderCodeBlockInfoMarker(node *ast.Node, entering bool) ast.WalkStatus { 489 | return ast.WalkContinue 490 | } 491 | 492 | func (r *DocxRenderer) renderCodeBlockOpenMarker(node *ast.Node, entering bool) ast.WalkStatus { 493 | return ast.WalkContinue 494 | } 495 | 496 | func (r *DocxRenderer) renderEmojiAlias(node *ast.Node, entering bool) ast.WalkStatus { 497 | return ast.WalkContinue 498 | } 499 | 500 | func (r *DocxRenderer) renderEmojiImg(node *ast.Node, entering bool) ast.WalkStatus { 501 | return ast.WalkContinue 502 | } 503 | 504 | func (r *DocxRenderer) renderEmojiUnicode(node *ast.Node, entering bool) ast.WalkStatus { 505 | return ast.WalkContinue 506 | } 507 | 508 | func (r *DocxRenderer) renderEmoji(node *ast.Node, entering bool) ast.WalkStatus { 509 | // 暂不渲染 Emoji,字体似乎有问题 510 | return ast.WalkContinue 511 | } 512 | 513 | func (r *DocxRenderer) renderInlineMathCloseMarker(node *ast.Node, entering bool) ast.WalkStatus { 514 | return ast.WalkContinue 515 | } 516 | 517 | func (r *DocxRenderer) renderInlineMathContent(node *ast.Node, entering bool) ast.WalkStatus { 518 | if entering { 519 | r.renderCodeSpanLike(node.Tokens) 520 | } 521 | return ast.WalkContinue 522 | } 523 | 524 | func (r *DocxRenderer) renderInlineMathOpenMarker(node *ast.Node, entering bool) ast.WalkStatus { 525 | return ast.WalkContinue 526 | } 527 | 528 | func (r *DocxRenderer) renderInlineMath(node *ast.Node, entering bool) ast.WalkStatus { 529 | return ast.WalkContinue 530 | } 531 | 532 | func (r *DocxRenderer) renderMathBlockCloseMarker(node *ast.Node, entering bool) ast.WalkStatus { 533 | return ast.WalkContinue 534 | } 535 | 536 | func (r *DocxRenderer) renderMathBlockContent(node *ast.Node, entering bool) ast.WalkStatus { 537 | if entering { 538 | r.renderCodeBlockLike(node.Tokens) 539 | } 540 | return ast.WalkContinue 541 | } 542 | 543 | func (r *DocxRenderer) renderMathBlockOpenMarker(node *ast.Node, entering bool) ast.WalkStatus { 544 | return ast.WalkContinue 545 | } 546 | 547 | func (r *DocxRenderer) renderMathBlock(node *ast.Node, entering bool) ast.WalkStatus { 548 | return ast.WalkContinue 549 | } 550 | 551 | func (r *DocxRenderer) renderTableCell(node *ast.Node, entering bool) ast.WalkStatus { 552 | //if entering { 553 | // // TODO: table align 554 | // //var attrs [][]string 555 | // //switch node.TableCellAlign { 556 | // //case 1: 557 | // // attrs = append(attrs, []string{"align", "left"}) 558 | // //case 2: 559 | // // attrs = append(attrs, []string{"align", "center"}) 560 | // //case 3: 561 | // // attrs = append(attrs, []string{"align", "right"}) 562 | // //} 563 | // x := r.pdf.GetX() 564 | // cols := float64(r.tableCols(node)) 565 | // maxWidth := (r.pageSize.W - r.margin*2) / cols 566 | // if node.Parent.FirstChild != node { 567 | // prevWidth, _ := r.pdf.MeasureTextWidth(util.BytesToStr(node.Previous.TableCellContent)) 568 | // x += maxWidth - prevWidth 569 | // r.pdf.SetX(x) 570 | // } 571 | // // TODO: table border 572 | // // r.pdf.RectFromUpperLeftWithStyle(x, r.pdf.GetY(), maxWidth, r.lineHeight, "D") 573 | // r.pdf.SetX(r.pdf.GetX() + 4) 574 | // r.pdf.SetY(r.pdf.GetY() + 4) 575 | //} else { 576 | // r.pdf.SetX(r.pdf.GetX() - 4) 577 | // r.pdf.SetY(r.pdf.GetY() - 4) 578 | //} 579 | return ast.WalkContinue 580 | } 581 | 582 | func (r *DocxRenderer) tableCols(cell *ast.Node) int { 583 | for parent := cell.Parent; nil != parent; parent = parent.Parent { 584 | if nil != parent.TableAligns { 585 | return len(parent.TableAligns) 586 | } 587 | } 588 | return 0 589 | } 590 | 591 | func (r *DocxRenderer) renderTableRow(node *ast.Node, entering bool) ast.WalkStatus { 592 | r.Newline() 593 | return ast.WalkContinue 594 | } 595 | 596 | func (r *DocxRenderer) renderTableHead(node *ast.Node, entering bool) ast.WalkStatus { 597 | //if entering { 598 | // r.pushPara(&Font{"bold", "B", r.fontSize}) 599 | //} else { 600 | // r.popFont() 601 | //} 602 | return ast.WalkContinue 603 | } 604 | 605 | func (r *DocxRenderer) renderTable(node *ast.Node, entering bool) ast.WalkStatus { 606 | //if entering { 607 | // r.pdf.SetY(r.pdf.GetY() + 6) 608 | //} else { 609 | // r.pdf.SetY(r.pdf.GetY() + 6) 610 | // r.Newline() 611 | //} 612 | return ast.WalkContinue 613 | } 614 | 615 | func (r *DocxRenderer) renderStrikethrough(node *ast.Node, entering bool) ast.WalkStatus { 616 | if entering { 617 | run := r.peekPara().AddRun() 618 | r.pushRun(&run) 619 | run.Properties().SetStrikeThrough(true) 620 | } else { 621 | r.popRun() 622 | r.reRun() 623 | } 624 | return ast.WalkContinue 625 | } 626 | 627 | func (r *DocxRenderer) renderStrikethrough1OpenMarker(node *ast.Node, entering bool) ast.WalkStatus { 628 | return ast.WalkContinue 629 | } 630 | 631 | func (r *DocxRenderer) renderStrikethrough1CloseMarker(node *ast.Node, entering bool) ast.WalkStatus { 632 | return ast.WalkContinue 633 | } 634 | 635 | func (r *DocxRenderer) renderStrikethrough2OpenMarker(node *ast.Node, entering bool) ast.WalkStatus { 636 | return ast.WalkContinue 637 | } 638 | 639 | func (r *DocxRenderer) renderStrikethrough2CloseMarker(node *ast.Node, entering bool) ast.WalkStatus { 640 | return ast.WalkContinue 641 | } 642 | 643 | func (r *DocxRenderer) renderLinkTitle(node *ast.Node, entering bool) ast.WalkStatus { 644 | return ast.WalkContinue 645 | } 646 | 647 | func (r *DocxRenderer) renderLinkDest(node *ast.Node, entering bool) ast.WalkStatus { 648 | return ast.WalkContinue 649 | } 650 | 651 | func (r *DocxRenderer) renderLinkSpace(node *ast.Node, entering bool) ast.WalkStatus { 652 | return ast.WalkContinue 653 | } 654 | 655 | func (r *DocxRenderer) renderLinkText(node *ast.Node, entering bool) ast.WalkStatus { 656 | if entering { 657 | if ast.NodeImage != node.Parent.Type { 658 | r.Write(node.Tokens) 659 | } 660 | } 661 | return ast.WalkContinue 662 | } 663 | 664 | func (r *DocxRenderer) renderCloseParen(node *ast.Node, entering bool) ast.WalkStatus { 665 | return ast.WalkContinue 666 | } 667 | 668 | func (r *DocxRenderer) renderOpenParen(node *ast.Node, entering bool) ast.WalkStatus { 669 | return ast.WalkContinue 670 | } 671 | 672 | func (r *DocxRenderer) renderCloseBracket(node *ast.Node, entering bool) ast.WalkStatus { 673 | return ast.WalkContinue 674 | } 675 | 676 | func (r *DocxRenderer) renderOpenBracket(node *ast.Node, entering bool) ast.WalkStatus { 677 | return ast.WalkContinue 678 | } 679 | 680 | func (r *DocxRenderer) renderBang(node *ast.Node, entering bool) ast.WalkStatus { 681 | return ast.WalkContinue 682 | } 683 | 684 | func (r *DocxRenderer) renderImage(node *ast.Node, entering bool) ast.WalkStatus { 685 | if entering { 686 | if 0 == r.DisableTags { 687 | destTokens := node.ChildByType(ast.NodeLinkDest).Tokens 688 | src := util.BytesToStr(destTokens) 689 | src, ok, isTemp := r.downloadImg(src) 690 | if ok { 691 | img, _ := common.ImageFromFile(src) 692 | imgRef, _ := r.doc.AddImage(img) 693 | inline, _ := r.peekRun().AddDrawingInline(imgRef) 694 | width, height := r.getImgSize(src) 695 | inline.SetSize(measurement.Distance(width), measurement.Distance(height)) 696 | if isTemp { 697 | r.images = append(r.images, src) 698 | } 699 | } 700 | } 701 | r.DisableTags++ 702 | return ast.WalkContinue 703 | } 704 | 705 | r.DisableTags-- 706 | if 0 == r.DisableTags { 707 | //r.WriteString("\"") 708 | //if title := node.ChildByType(ast.NodeLinkTitle); nil != title && nil != title.Tokens { 709 | // r.WriteString(" title=\"") 710 | // r.Write(title.Tokens) 711 | // r.WriteString("\"") 712 | //} 713 | //r.WriteString(" />") 714 | } 715 | return ast.WalkContinue 716 | } 717 | 718 | func (r *DocxRenderer) renderLink(node *ast.Node, entering bool) ast.WalkStatus { 719 | if entering { 720 | dest := node.ChildByType(ast.NodeLinkDest) 721 | destTokens := dest.Tokens 722 | destTokens = r.RelativePath(destTokens) 723 | para := r.peekPara() 724 | link := para.AddHyperLink() 725 | link.SetTarget(util.BytesToStr(destTokens)) 726 | run := link.AddRun() 727 | run.Properties().SetStyle("Hyperlink") 728 | r.pushRun(&run) 729 | } else { 730 | r.popRun() 731 | r.reRun() 732 | } 733 | return ast.WalkContinue 734 | } 735 | 736 | func (r *DocxRenderer) renderHTML(node *ast.Node, entering bool) ast.WalkStatus { 737 | if entering { 738 | r.renderCodeBlockLike(node.Tokens) 739 | } 740 | return ast.WalkContinue 741 | } 742 | 743 | func (r *DocxRenderer) renderInlineHTML(node *ast.Node, entering bool) ast.WalkStatus { 744 | if entering { 745 | r.renderCodeSpanLike(node.Tokens) 746 | } 747 | return ast.WalkContinue 748 | } 749 | 750 | func (r *DocxRenderer) renderDocument(node *ast.Node, entering bool) ast.WalkStatus { 751 | return ast.WalkContinue 752 | } 753 | 754 | func (r *DocxRenderer) Save(docxPath string) { 755 | err := r.doc.SaveToFile(docxPath) 756 | for _, img := range r.images { 757 | os.Remove(img) 758 | } 759 | if nil != err { 760 | logger.Fatal(err) 761 | } 762 | } 763 | 764 | func (r *DocxRenderer) renderParagraph(node *ast.Node, entering bool) ast.WalkStatus { 765 | inList := false 766 | grandparent := node.Parent.Parent 767 | inTightList := false 768 | if nil != grandparent && ast.NodeList == grandparent.Type { 769 | inList = true 770 | inTightList = grandparent.Tight 771 | } 772 | 773 | if inTightList { 774 | if entering { 775 | para := r.peekPara() 776 | run := para.AddRun() 777 | r.pushRun(&run) 778 | } else { 779 | r.popRun() 780 | } 781 | return ast.WalkContinue 782 | } 783 | 784 | isFirstParaInList := false 785 | if inList { 786 | isFirstParaInList = node.Parent.FirstChild == node 787 | } 788 | 789 | if entering { 790 | if !inList { 791 | para := r.doc.AddParagraph() 792 | r.pushPara(¶) 793 | run := para.AddRun() 794 | r.pushRun(&run) 795 | } else { 796 | if inTightList { 797 | para := r.peekPara() 798 | run := para.AddRun() 799 | r.pushRun(&run) 800 | } else { 801 | if isFirstParaInList { 802 | para := r.peekPara() 803 | run := para.AddRun() 804 | r.pushRun(&run) 805 | } else { 806 | para := r.doc.AddParagraph() 807 | r.pushPara(¶) 808 | run := para.AddRun() 809 | r.pushRun(&run) 810 | } 811 | } 812 | } 813 | } else { 814 | if !inList { 815 | r.peekRun().AddBreak() 816 | r.popRun() 817 | r.popPara() 818 | } else { 819 | if inTightList { 820 | r.popRun() 821 | } else { 822 | if isFirstParaInList { 823 | r.popRun() 824 | } else { 825 | r.popRun() 826 | r.popPara() 827 | } 828 | } 829 | } 830 | } 831 | return ast.WalkContinue 832 | } 833 | 834 | func (r *DocxRenderer) renderText(node *ast.Node, entering bool) ast.WalkStatus { 835 | if entering { 836 | text := util.BytesToStr(node.Tokens) 837 | r.WriteString(text) 838 | } 839 | return ast.WalkContinue 840 | } 841 | 842 | func (r *DocxRenderer) renderCodeSpan(node *ast.Node, entering bool) ast.WalkStatus { 843 | return ast.WalkContinue 844 | } 845 | 846 | func (r *DocxRenderer) renderCodeSpanOpenMarker(node *ast.Node, entering bool) ast.WalkStatus { 847 | return ast.WalkContinue 848 | } 849 | 850 | func (r *DocxRenderer) renderCodeSpanContent(node *ast.Node, entering bool) ast.WalkStatus { 851 | if entering { 852 | r.renderCodeSpanLike(node.Tokens) 853 | } 854 | return ast.WalkContinue 855 | } 856 | 857 | func (r *DocxRenderer) renderCodeSpanCloseMarker(node *ast.Node, entering bool) ast.WalkStatus { 858 | return ast.WalkContinue 859 | } 860 | 861 | func (r *DocxRenderer) renderEmphasis(node *ast.Node, entering bool) ast.WalkStatus { 862 | if entering { 863 | run := r.peekPara().AddRun() 864 | r.pushRun(&run) 865 | run.Properties().SetItalic(true) 866 | } else { 867 | r.popRun() 868 | r.reRun() 869 | } 870 | return ast.WalkContinue 871 | } 872 | 873 | func (r *DocxRenderer) renderEmAsteriskOpenMarker(node *ast.Node, entering bool) ast.WalkStatus { 874 | return ast.WalkContinue 875 | } 876 | 877 | func (r *DocxRenderer) renderEmAsteriskCloseMarker(node *ast.Node, entering bool) ast.WalkStatus { 878 | return ast.WalkContinue 879 | } 880 | 881 | func (r *DocxRenderer) renderEmUnderscoreOpenMarker(node *ast.Node, entering bool) ast.WalkStatus { 882 | return ast.WalkContinue 883 | } 884 | 885 | func (r *DocxRenderer) renderEmUnderscoreCloseMarker(node *ast.Node, entering bool) ast.WalkStatus { 886 | return ast.WalkContinue 887 | } 888 | 889 | func (r *DocxRenderer) renderStrong(node *ast.Node, entering bool) ast.WalkStatus { 890 | if entering { 891 | run := r.peekPara().AddRun() 892 | r.pushRun(&run) 893 | run.Properties().SetBold(true) 894 | } else { 895 | r.popRun() 896 | r.reRun() 897 | } 898 | return ast.WalkContinue 899 | } 900 | 901 | func (r *DocxRenderer) renderStrongA6kOpenMarker(node *ast.Node, entering bool) ast.WalkStatus { 902 | return ast.WalkContinue 903 | } 904 | 905 | func (r *DocxRenderer) renderStrongA6kCloseMarker(node *ast.Node, entering bool) ast.WalkStatus { 906 | return ast.WalkContinue 907 | } 908 | 909 | func (r *DocxRenderer) renderStrongU8eOpenMarker(node *ast.Node, entering bool) ast.WalkStatus { 910 | return ast.WalkContinue 911 | } 912 | 913 | func (r *DocxRenderer) renderStrongU8eCloseMarker(node *ast.Node, entering bool) ast.WalkStatus { 914 | return ast.WalkContinue 915 | } 916 | 917 | func (r *DocxRenderer) renderBlockquote(node *ast.Node, entering bool) ast.WalkStatus { 918 | return ast.WalkContinue 919 | } 920 | 921 | func (r *DocxRenderer) renderBlockquoteMarker(node *ast.Node, entering bool) ast.WalkStatus { 922 | return ast.WalkContinue 923 | } 924 | 925 | func (r *DocxRenderer) renderHeading(node *ast.Node, entering bool) ast.WalkStatus { 926 | if entering { 927 | para := r.doc.AddParagraph() 928 | r.pushPara(¶) 929 | run := para.AddRun() 930 | r.pushRun(&run) 931 | props := run.Properties() 932 | props.SetBold(true) 933 | 934 | switch node.HeadingLevel { 935 | case 1: 936 | props.SetSize(measurement.Distance(r.heading1Size)) 937 | props.SetStyle("Heading1") 938 | case 2: 939 | props.SetSize(measurement.Distance(r.heading2Size)) 940 | props.SetStyle("Heading2") 941 | case 3: 942 | props.SetSize(measurement.Distance(r.heading3Size)) 943 | props.SetStyle("Heading3") 944 | case 4: 945 | props.SetSize(measurement.Distance(r.heading4Size)) 946 | props.SetStyle("Heading4") 947 | case 5: 948 | props.SetSize(measurement.Distance(r.heading5Size)) 949 | props.SetStyle("Heading5") 950 | case 6: 951 | props.SetSize(measurement.Distance(r.heading6Size)) 952 | props.SetStyle("Heading6") 953 | default: 954 | props.SetSize(measurement.Distance(r.heading3Size)) 955 | props.SetStyle("Heading3") 956 | } 957 | } else { 958 | r.popPara() 959 | r.popRun() 960 | r.Newline() 961 | } 962 | return ast.WalkContinue 963 | } 964 | 965 | func (r *DocxRenderer) renderHeadingC8hMarker(node *ast.Node, entering bool) ast.WalkStatus { 966 | return ast.WalkContinue 967 | } 968 | 969 | func (r *DocxRenderer) renderList(node *ast.Node, entering bool) ast.WalkStatus { 970 | if !entering { 971 | r.Newline() 972 | } 973 | return ast.WalkContinue 974 | } 975 | 976 | func (r *DocxRenderer) renderListItem(node *ast.Node, entering bool) ast.WalkStatus { 977 | if entering { 978 | paragraph := r.doc.AddParagraph() 979 | r.pushPara(¶graph) 980 | 981 | nestedLevel := r.countParentContainerBlocks(node) - 1 982 | indent := float64(nestedLevel * 22) 983 | 984 | if 3 == node.ListData.Typ && "" != r.Options.GFMTaskListItemClass && 985 | nil != node.FirstChild && nil != node.FirstChild.FirstChild && ast.NodeTaskListItemMarker == node.FirstChild.FirstChild.Type { 986 | r.WriteString(fmt.Sprintf("%s", node.ListData.Marker)) 987 | } else { 988 | definition := r.doc.Numbering.AddDefinition() 989 | level := definition.AddLevel() 990 | level.Properties().SetLeftIndent(measurement.Distance(indent)) 991 | if 0 != node.BulletChar { 992 | level.SetFormat(wml.ST_NumberFormatBullet) 993 | level.RunProperties().SetSize(6) 994 | level.SetText("●") 995 | } else { 996 | level.Properties().SetStartIndent(30) 997 | level.SetFormat(wml.ST_NumberFormatDecimal) 998 | level.SetText(fmt.Sprint(node.Num) + ".") 999 | } 1000 | paragraph.SetNumberingDefinition(definition) 1001 | } 1002 | } else { 1003 | r.popPara() 1004 | } 1005 | return ast.WalkContinue 1006 | } 1007 | 1008 | func (r *DocxRenderer) renderTaskListItemMarker(node *ast.Node, entering bool) ast.WalkStatus { 1009 | if entering { 1010 | var attrs [][]string 1011 | if node.TaskListItemChecked { 1012 | attrs = append(attrs, []string{"checked", ""}) 1013 | } 1014 | attrs = append(attrs, []string{"disabled", ""}, []string{"type", "checkbox"}) 1015 | //r.tag("input", attrs, true) 1016 | } 1017 | return ast.WalkContinue 1018 | } 1019 | 1020 | func (r *DocxRenderer) renderThematicBreak(node *ast.Node, entering bool) ast.WalkStatus { 1021 | //r.Newline() 1022 | //r.pdf.SetY(r.pdf.GetY() + 14) 1023 | //r.pdf.SetStrokeColor(106, 115, 125) 1024 | //r.pdf.Line(r.pdf.GetX()+float64(r.fontSize), r.pdf.GetY(), r.pageSize.W-r.margin-float64(r.fontSize), r.pdf.GetY()) 1025 | //r.pdf.SetY(r.pdf.GetY() + 12) 1026 | //r.pdf.SetStrokeColor(0, 0, 0) 1027 | //r.Newline() 1028 | return ast.WalkContinue 1029 | } 1030 | 1031 | func (r *DocxRenderer) renderHardBreak(node *ast.Node, entering bool) ast.WalkStatus { 1032 | if entering { 1033 | r.Newline() 1034 | } 1035 | return ast.WalkContinue 1036 | } 1037 | 1038 | func (r *DocxRenderer) renderSoftBreak(node *ast.Node, entering bool) ast.WalkStatus { 1039 | if entering { 1040 | r.Newline() 1041 | } 1042 | return ast.WalkContinue 1043 | } 1044 | 1045 | func (r *DocxRenderer) pushPara(para *document.Paragraph) { 1046 | r.paragraphs = append(r.paragraphs, para) 1047 | } 1048 | 1049 | func (r *DocxRenderer) popPara() *document.Paragraph { 1050 | ret := r.paragraphs[len(r.paragraphs)-1] 1051 | r.paragraphs = r.paragraphs[:len(r.paragraphs)-1] 1052 | return ret 1053 | } 1054 | 1055 | func (r *DocxRenderer) peekPara() *document.Paragraph { 1056 | return r.paragraphs[len(r.paragraphs)-1] 1057 | } 1058 | 1059 | func (r *DocxRenderer) pushRun(run *document.Run) { 1060 | r.runs = append(r.runs, run) 1061 | } 1062 | 1063 | func (r *DocxRenderer) popRun() *document.Run { 1064 | ret := r.runs[len(r.runs)-1] 1065 | r.runs = r.runs[:len(r.runs)-1] 1066 | return ret 1067 | } 1068 | 1069 | func (r *DocxRenderer) peekRun() *document.Run { 1070 | if 1 > len(r.runs) { 1071 | return nil 1072 | } 1073 | 1074 | return r.runs[len(r.runs)-1] 1075 | } 1076 | 1077 | func (r *DocxRenderer) countParentContainerBlocks(n *ast.Node) (ret int) { 1078 | for parent := n.Parent; nil != parent; parent = parent.Parent { 1079 | if ast.NodeBlockquote == parent.Type || ast.NodeList == parent.Type { 1080 | ret++ 1081 | } 1082 | } 1083 | return 1084 | } 1085 | 1086 | // WriteByte 输出一个字节 c。 1087 | func (r *DocxRenderer) WriteByte(c byte) { 1088 | r.WriteString(string(c)) 1089 | } 1090 | 1091 | // Write 输出指定的字节数组 content。 1092 | func (r *DocxRenderer) Write(content []byte) { 1093 | r.WriteString(util.BytesToStr(content)) 1094 | } 1095 | 1096 | // WriteString 输出指定的字符串 content。 1097 | func (r *DocxRenderer) WriteString(content string) { 1098 | if length := len(content); 0 < length { 1099 | run := r.peekRun() 1100 | run.AddText(content) 1101 | r.LastOut = content[length-1] 1102 | } 1103 | } 1104 | 1105 | // Newline 会在最新内容不是换行符 \n 时输出一个换行符。 1106 | func (r *DocxRenderer) Newline() { 1107 | if lex.ItemNewline != r.LastOut { 1108 | r.doc.AddParagraph() 1109 | r.LastOut = lex.ItemNewline 1110 | } 1111 | } 1112 | 1113 | func (r *DocxRenderer) downloadImg(src string) (localPath string, ok, isTemp bool) { 1114 | if strings.HasPrefix(src, "//") { 1115 | src = "https:" + src 1116 | } 1117 | 1118 | u, err := url.Parse(src) 1119 | if nil != err { 1120 | logger.Infof("image src [%s] is not an valid URL, treat it as local path", src) 1121 | return src, true, false 1122 | } 1123 | 1124 | if !strings.HasPrefix(u.Scheme, "http") { 1125 | logger.Infof("image src [%s] scheme is not [http] or [https], treat it as local path", src) 1126 | return src, true, false 1127 | } 1128 | 1129 | src = r.qiniuImgProcessing(src) 1130 | u, _ = url.Parse(src) 1131 | 1132 | client := http.Client{ 1133 | Timeout: 5 * time.Second, 1134 | } 1135 | req := &http.Request{ 1136 | Header: http.Header{ 1137 | "User-Agent": []string{"Lute-DOCX; +https://github.com/88250/lute-docx"}, 1138 | }, 1139 | URL: u, 1140 | } 1141 | resp, err := client.Do(req) 1142 | if nil != err { 1143 | logger.Warnf("download image [%s] failed: %s", src, err) 1144 | return src, false, false 1145 | } 1146 | defer resp.Body.Close() 1147 | if 200 != resp.StatusCode { 1148 | logger.Warnf("download image [%s] failed, status code is [%d]", src, resp.StatusCode) 1149 | return src, false, false 1150 | } 1151 | 1152 | data, err := ioutil.ReadAll(resp.Body) 1153 | file, err := ioutil.TempFile("", "lute-docx.img.") 1154 | if nil != err { 1155 | logger.Warnf("create temp image [%s] failed: %s", src, err) 1156 | return src, false, false 1157 | } 1158 | _, err = file.Write(data) 1159 | if nil != err { 1160 | logger.Warnf("write temp image [%s] failed: %s", src, err) 1161 | return src, false, false 1162 | } 1163 | file.Close() 1164 | return file.Name(), true, true 1165 | } 1166 | 1167 | // qiniuImgProcessing 七牛云图片样式处理。 1168 | func (r *DocxRenderer) qiniuImgProcessing(src string) string { 1169 | if !strings.Contains(src, "img.hacpai.com") && !strings.Contains(src, "b3logfile.com") && !strings.Contains(src, "imageView") { 1170 | return src 1171 | } 1172 | 1173 | if 0 < strings.Index(src, "?") { 1174 | src = src[:strings.Index(src, "?")] 1175 | } 1176 | 1177 | //maxWidth := int(math.Round(r.pageSize.W-r.margin*2) * 128 / 72) 1178 | //style := "imageView2/2/w/%d/interlace/1/format/jpg" 1179 | //style = fmt.Sprintf(style, maxWidth) 1180 | //src += "?" + style 1181 | return src 1182 | } 1183 | 1184 | func (r *DocxRenderer) getImgSize(imgPath string) (width, height float64) { 1185 | file, err := os.Open(imgPath) 1186 | if nil != err { 1187 | logger.Fatal(err) 1188 | } 1189 | img, _, err := image.Decode(file) 1190 | if nil != err { 1191 | logger.Fatal(err) 1192 | } 1193 | file.Close() 1194 | 1195 | imageRect := img.Bounds() 1196 | k := 1 1197 | w := -128 1198 | h := -128 1199 | if w < 0 { 1200 | w = -imageRect.Dx() * 72 / w / k 1201 | } 1202 | if h < 0 { 1203 | h = -imageRect.Dy() * 72 / h / k 1204 | } 1205 | if w == 0 { 1206 | w = h * imageRect.Dx() / imageRect.Dy() 1207 | } 1208 | if h == 0 { 1209 | h = w * imageRect.Dy() / imageRect.Dx() 1210 | } 1211 | return float64(w), float64(h) 1212 | } 1213 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/88250/lute-docx 2 | 3 | go 1.14 4 | 5 | require ( 6 | github.com/88250/gulu v1.1.2 7 | github.com/88250/lute v1.7.1-0.20201227150112-460780f34e08 8 | github.com/unidoc/unioffice v1.4.0 9 | golang.org/x/text v0.3.4 // indirect 10 | ) 11 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/88250/gulu v1.1.2 h1:zgnftJgG4knQ97EPwDhQRKCgos40qRIafTWgGcP5EG4= 2 | github.com/88250/gulu v1.1.2/go.mod h1:a2POIziN+QFeNT4Mj7FHH2lz1HEaFlMRF6wPE0NHM4U= 3 | github.com/88250/lute v1.6.7-0.20201123095407-ba1f0facb9a0 h1:IFzR9Dg7q+i4qK8wd0MzekUsxid6e+tnbvNzsOECChU= 4 | github.com/88250/lute v1.6.7-0.20201123095407-ba1f0facb9a0/go.mod h1:APx6IhxzrUGJqmIalKYomjVLrO4yw/PzEBUtYxpMrfk= 5 | github.com/88250/lute v1.7.1-0.20201227150112-460780f34e08 h1:QcG/1nAcBO1W1dKwZFZhPnXdkS8E5BVA/9EO9j9kG8g= 6 | github.com/88250/lute v1.7.1-0.20201227150112-460780f34e08/go.mod h1:APx6IhxzrUGJqmIalKYomjVLrO4yw/PzEBUtYxpMrfk= 7 | github.com/alecthomas/assert v0.0.0-20170929043011-405dbfeb8e38 h1:smF2tmSOzy2Mm+0dGI2AIUHY+w0BUc+4tn40djz7+6U= 8 | github.com/alecthomas/assert v0.0.0-20170929043011-405dbfeb8e38/go.mod h1:r7bzyVFMNntcxPZXK3/+KdruV1H5KSlyVY0gc+NgInI= 9 | github.com/alecthomas/chroma v0.8.2 h1:x3zkuE2lUk/RIekyAJ3XRqSCP4zwWDfcw/YJCuCAACg= 10 | github.com/alecthomas/chroma v0.8.2/go.mod h1:sko8vR34/90zvl5QdcUdvzL3J8NKjAUx9va9jPuFNoM= 11 | github.com/alecthomas/colour v0.0.0-20160524082231-60882d9e2721/go.mod h1:QO9JBoKquHd+jz9nshCh40fOfO+JzsoXy8qTHF68zU0= 12 | github.com/alecthomas/colour v0.1.0 h1:nOE9rJm6dsZ66RGWYSFrXw461ZIt9A6+nHgL7FRrDUk= 13 | github.com/alecthomas/colour v0.1.0/go.mod h1:QO9JBoKquHd+jz9nshCh40fOfO+JzsoXy8qTHF68zU0= 14 | github.com/alecthomas/kong v0.2.4/go.mod h1:kQOmtJgV+Lb4aj+I2LEn40cbtawdWJ9Y8QLq+lElKxE= 15 | github.com/alecthomas/repr v0.0.0-20180818092828-117648cd9897/go.mod h1:xTS7Pm1pD1mvyM075QCDSRqH6qRLXylzS24ZTpRiSzQ= 16 | github.com/alecthomas/repr v0.0.0-20200325044227-4184120f674c h1:MVVbswUlqicyj8P/JljoocA7AyCo62gzD0O7jfvrhtE= 17 | github.com/alecthomas/repr v0.0.0-20200325044227-4184120f674c/go.mod h1:xTS7Pm1pD1mvyM075QCDSRqH6qRLXylzS24ZTpRiSzQ= 18 | github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= 19 | github.com/danwakefield/fnmatch v0.0.0-20160403171240-cbb64ac3d964 h1:y5HC9v93H5EPKqaS1UYVg1uYah5Xf51mBfIoWehClUQ= 20 | github.com/danwakefield/fnmatch v0.0.0-20160403171240-cbb64ac3d964/go.mod h1:Xd9hchkHSWYkEqJwUGisez3G1QY8Ryz0sdWrLPMGjLk= 21 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 22 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 23 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 24 | github.com/dlclark/regexp2 v1.2.0 h1:8sAhBGEM0dRWogWqWyQeIJnxjWO6oIjl8FKqREDsGfk= 25 | github.com/dlclark/regexp2 v1.2.0/go.mod h1:2pZnwuY/m+8K6iRw6wQdMtk+rH5tNGR1i55kozfMjCc= 26 | github.com/dlclark/regexp2 v1.4.0 h1:F1rxgk7p4uKjwIQxBs9oAXe5CqrXlCduYEJvrF4u93E= 27 | github.com/dlclark/regexp2 v1.4.0/go.mod h1:2pZnwuY/m+8K6iRw6wQdMtk+rH5tNGR1i55kozfMjCc= 28 | github.com/gopherjs/gopherjs v0.0.0-20200217142428-fce0ec30dd00 h1:l5lAOZEym3oK3SQ2HBHWsJUfbNBiTXJDeW2QDxw9AQ0= 29 | github.com/gopherjs/gopherjs v0.0.0-20200217142428-fce0ec30dd00/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= 30 | github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= 31 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= 32 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= 33 | github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= 34 | github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= 35 | github.com/mattn/go-colorable v0.1.6/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= 36 | github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY= 37 | github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= 38 | github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= 39 | github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= 40 | github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 41 | github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 42 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 43 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 44 | github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= 45 | github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0= 46 | github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= 47 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 48 | github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= 49 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= 50 | github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= 51 | github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0= 52 | github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 53 | github.com/unidoc/unioffice v1.4.0 h1:yl+TbZJu2GTVYAYvu51wppj0R+fPC67xzVcy91qgrzI= 54 | github.com/unidoc/unioffice v1.4.0/go.mod h1:7wl8btOkZW1TfqfpDWoujRXkUpowwisGRYDo7COHBiI= 55 | golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 56 | golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 57 | golang.org/x/sys v0.0.0-20200413165638-669c56c373c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 58 | golang.org/x/sys v0.0.0-20200918174421-af09f7315aff h1:1CPUrky56AcgSpxz/KfgzQWzfG09u5YOL8MvPYBlrL8= 59 | golang.org/x/sys v0.0.0-20200918174421-af09f7315aff/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 60 | golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs= 61 | golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= 62 | golang.org/x/text v0.3.4 h1:0YWbFKbhXG/wIiuHDSKpS0Iy7FSA+u45VtBMfQcFTTc= 63 | golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 64 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 65 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 66 | gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 67 | gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b h1:QRR6H1YWRnHb4Y/HeNFCTJLFVxaq6wH4YuVdsUOr75U= 68 | gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 69 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 70 | gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 71 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 72 | gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776 h1:tQIYjPdBoyREyB9XMu+nnTclpTYkz2zFM+lzLJFO4gQ= 73 | gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 74 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | // Lute DOCX - 一款将 Markdown 文本转换为 Word 文档 (.docx) 的小工具 2 | // Copyright (c) 2020-present, b3log.org 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Affero General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Affero General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Affero General Public License 15 | // along with this program. If not, see . 16 | 17 | package main 18 | 19 | import ( 20 | "bytes" 21 | "flag" 22 | "github.com/88250/lute/render" 23 | "io/ioutil" 24 | "os" 25 | "strings" 26 | 27 | "github.com/88250/gulu" 28 | "github.com/88250/lute/parse" 29 | ) 30 | 31 | var logger *gulu.Logger 32 | 33 | func init() { 34 | logger = gulu.Log.NewLogger(os.Stdout) 35 | } 36 | 37 | func main() { 38 | argMdPath := flag.String("mdPath", "D:/88250/lute-docx/sample.md", "待转换的 Markdown 文件路径") 39 | argSavePath := flag.String("savePath", "D:/88250/lute-docx/sample.docx", "转换后 DOCX 的保存路径") 40 | 41 | argCoverTitle := flag.String("coverTitle", "Lute DOCX - Markdown 生成 DOCX", "封面 - 标题") 42 | argCoverAuthor := flag.String("coverAuthor", "88250", "封面 - 作者") 43 | argCoverAuthorLink := flag.String("coverAuthorLink", "https://ld246.com/member/88250", "封面 - 作者链接") 44 | argCoverLink := flag.String("coverLink", "https://github.com/88250/lute-docx", "封面 - 原文链接") 45 | argCoverSource := flag.String("coverSource", "GitHub", "封面 - 来源网站") 46 | argCoverSourceLink := flag.String("coverSourceLink", "https://github.com", "封面 - 来源网站链接") 47 | argCoverLicense := flag.String("coverLicense", "署名-相同方式共享 4.0 国际 (CC BY-SA 4.0)", "封面 - 文档许可协议") 48 | argCoverLicenseLink := flag.String("coverLicenseLink", "https://creativecommons.org/licenses/by-sa/4.0/", "封面 - 文档许可协议链接") 49 | argCoverLogoLink := flag.String("coverLogoLink", "https://static.b3log.org/images/brand/b3log-128.png", "封面 - 图标链接") 50 | argCoverLogoTitle := flag.String("coverLogoTitle", "B3log 开源", "封面 - 图标标题") 51 | argCoverLogoTitleLink := flag.String("coverLogoTitleLink", "https://b3log.org", "封面 - 图标标题链接") 52 | 53 | flag.Parse() 54 | 55 | mdPath := trimQuote(*argMdPath) 56 | savePath := trimQuote(*argSavePath) 57 | 58 | coverTitle := trimQuote(*argCoverTitle) 59 | coverAuthorLabel := "  作者:" 60 | coverAuthor := trimQuote(*argCoverAuthor) 61 | coverAuthorLink := trimQuote(*argCoverAuthorLink) 62 | coverLinkLabel := "原文链接:" 63 | coverLink := trimQuote(*argCoverLink) 64 | coverSourceLabel := "来源网站:" 65 | coverSource := trimQuote(*argCoverSource) 66 | coverSourceLink := trimQuote(*argCoverSourceLink) 67 | coverLicenseLabel := "许可协议:" 68 | coverLicense := trimQuote(*argCoverLicense) 69 | coverLicenseLink := trimQuote(*argCoverLicenseLink) 70 | coverLogoLink := trimQuote(*argCoverLogoLink) 71 | coverLogoTitle := trimQuote(*argCoverLogoTitle) 72 | coverLogoTitleLink := trimQuote(*argCoverLogoTitleLink) 73 | 74 | parseOptions := parse.NewOptions() 75 | parseOptions.AliasEmoji, parseOptions.EmojiAlias = parse.NewEmojis() 76 | 77 | markdown, err := ioutil.ReadFile(mdPath) 78 | if nil != err { 79 | logger.Fatal(err) 80 | } 81 | 82 | markdown = bytes.ReplaceAll(markdown, []byte("\t"), []byte(" ")) 83 | for emojiUnicode, emojiAlias := range parseOptions.EmojiAlias { 84 | markdown = bytes.ReplaceAll(markdown, []byte(emojiUnicode), []byte(":"+emojiAlias+":")) 85 | } 86 | 87 | tree := parse.Parse("", markdown, parseOptions) 88 | renderOptions := render.NewOptions() 89 | renderer := NewDocxRenderer(tree, renderOptions) 90 | renderer.Cover = &DocxCover{ 91 | Title: coverTitle, 92 | AuthorLabel: coverAuthorLabel, 93 | Author: coverAuthor, 94 | AuthorLink: coverAuthorLink, 95 | LinkLabel: coverLinkLabel, 96 | Link: coverLink, 97 | SourceLabel: coverSourceLabel, 98 | Source: coverSource, 99 | SourceLink: coverSourceLink, 100 | LicenseLabel: coverLicenseLabel, 101 | License: coverLicense, 102 | LicenseLink: coverLicenseLink, 103 | LogoLink: coverLogoLink, 104 | LogoTitle: coverLogoTitle, 105 | LogoTitleLink: coverLogoTitleLink, 106 | } 107 | renderer.RenderCover() 108 | 109 | renderer.Render() 110 | renderer.Save(savePath) 111 | 112 | logger.Info("completed") 113 | } 114 | 115 | func trimQuote(str string) string { 116 | return strings.Trim(str, "\"'") 117 | } 118 | -------------------------------------------------------------------------------- /sample.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/88250/lute-docx/b4d45ff8149cfdead7eea17c3995c4c49469060c/sample.docx -------------------------------------------------------------------------------- /sample.md: -------------------------------------------------------------------------------- 1 | ## 简介 2 | 3 | Lute DOCX 是一款将 Markdown 文本转换为 Word 文档 (.docx) 的小工具。通过 [Lute](https://github.com/88250/lute) 解析 Markdown 然后再通过 [unioffice](https://github.com/unidoc/unioffice) 生成 DOCX。 4 | 5 | ## 特性 6 | 7 | * 几乎支持所有 Markdown 语法元素 8 | * 图片会通过地址自动拉取并渲染 9 | * 支持封面配置 10 | 11 | ## 社区 12 | 13 | * [讨论区](https://ld246.com/tag/lute) 14 | * [报告问题](https://github.com/88250/lute-docx/issues/new) 15 | * 欢迎关注 B3log 开源社区微信公众号 `B3log开源` 16 | 17 | ![b3logos.png](https://b3logfile.com/file/2019/10/image-d3c00d78.png) 18 | 19 | ## 开源协议 20 | 21 | Lute DOCX 使用 [木兰宽松许可证, 第2版](http://license.coscl.org.cn/MulanPSL2) 开源协议。 22 | 23 | ## 鸣谢 24 | 25 | * [对中文语境优化的 Markdown 引擎 Lute](https://ld246.com/article/1567047822949) 26 | * [Go 实现的 Office 文档操作工具库](https://github.com/unidoc/unioffice) 27 | --------------------------------------------------------------------------------