Repository navigation
Expand file tree
/
Copy pathgdocs-me-up.js
More file actions
2326 lines (2135 loc) · 82.1 KB
/
Copy pathgdocs-me-up.js
File metadata and controls
2326 lines (2135 loc) · 82.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* google-docs-high-fidelity-export.js
*
* High-Fidelity Exporter for Google Docs
*
* Features:
* - **Named Styles**: Title, Subtitle, Headings (H1..H6) mapped to real HTML headings,
* with doc-based font sizing and inline styling (bold, italic, color, etc.).
* - **Heading Size Override**: Resets default <h1>.. <h6> to neutral size in CSS,
* so doc's inline size precisely controls final heading font.
* - **Line Spacing**: Honors doc's paragraph lineSpacing (e.g., 1.15, 1.5),
* plus spaceAbove/spaceBelow, and text indentation (indentFirstLine, indentStart, indentEnd).
* - **Right-to-Left Paragraphs**: Sets `dir="rtl"` for paragraphs whose style
* indicates RIGHT_TO_LEFT, flipping alignment START/END if needed. Includes comprehensive
* Unicode subset support (Arabic, Hebrew, Thai, Devanagari, etc.).
* - **Alignment**: PRESERVES doc-based alignment (CENTER, JUSTIFIED, etc.).
* - **Lists**: Bullet / Numbered lists, including RTL bullets if direction=RIGHT_TO_LEFT.
* - **Text Styling**: Bold, italic, underline, strikethrough, superscript, subscript,
* small caps, text color, background color, font family with weights.
* - **Paragraph Borders & Shading**: Supports top/bottom/left/right borders with colors
* and styles (solid, dotted, dashed, double), plus paragraph background colors.
* - **Pagination Control**: pageBreakBefore, keepLinesTogether, keepWithNext,
* avoidWidowAndOrphan for print-friendly layouts.
* - **Images**: Exact doc-based sizes, with transform scaling and translation.
* Supports image cropping (cropProperties), margins, and positioning.
* Exports images to an `images/` folder. Uses `max-width` / `max-height` so they
* never exceed doc's reported size or the container width.
* - **Table of Contents**: Indents each TOC entry based on the heading level of its
* linked heading (Heading 1 => level 1, etc.).
* - **Tables**: Exports Google Docs tables using <table>, <tr>, <td> with full support for:
* cell borders (per-cell), background colors, padding, colspan, rowspan.
* - **Horizontal Rules**: Renders horizontal rule elements as <hr>.
* - **Footnotes**: Renders footnote references with superscript links.
* - **Equations**: Basic equation support (rendered as code for now).
* - **Auto Text**: Page numbers and page counts (placeholders).
* - **Multi-Column Layouts**: Section breaks with column properties for multi-column text.
* - **Column Breaks**: Explicit column break rendering.
* - **Column Width**: Infers container width from doc's pageSize minus margins
* (with a small tweak). Then sets `.doc-content { max-width: ... }`.
* - **Google Fonts**: Gathers all distinct fonts used, generating a <link> to
* https://fonts.googleapis.com with multiple weights and comprehensive Unicode subsets
* for non-Latin scripts (Arabic, Hebrew, Greek, Cyrillic, etc.).
* - **Merging Text Runs**: Consecutive text runs with identical styling are combined
* into a single <span> to avoid excessive markup.
* - **Service Account Auth**: Reads from `SERVICE_ACCOUNT_KEY_FILE`, falling back to
* `service_account.json` beside this script. Requires the doc to be accessible with
* the given credentials.
*
* Usage:
* node google-docs-high-fidelity-export.js <DOC_ID> <OUTPUT_DIR> [options]
*
* Example:
* node google-docs-high-fidelity-export.js 1AbCdEfgHIjKLMnOP <my-export-dir>
*
* Then open <my-export-dir>/index.html to see the rendered doc.
*
* Dependencies:
* - Node.js
* - "googleapis" library (npm install googleapis)
* - A valid Google service account JSON key or other OAuth method
*
* This script merges doc-based styling with neutral heading overrides so your headings
* appear at the exact doc size without default HTML heading inflation. Right-to-left,
* justification, bullet-lists, images, tables, borders, and more are handled for a truly
* "high-fidelity" offline representation of your Google Doc with extensive support for
* international and non-Latin scripts.
*/
const fs = require('fs');
const path = require('path');
const { google } = require('googleapis');
const { StyleRegistry, joinClasses } = require('./lib/styles');
const { writeOptimizedImage } = require('./lib/images');
const { imageCrop, cropImageStyle } = require('./lib/image-crop');
const { trackFont, buildGoogleFontsLink } = require('./lib/google-fonts');
const {
collectFontFamilies,
loadGoogleFontMetrics,
naturalLineHeight,
lineHeightFor
} = require('./lib/font-metrics');
// ------------- CONSTANTS -------------
// Indentation thresholds for inferring nesting levels (in points)
const INDENT_LEVEL_0_MAX = 40; // Items with indent <= 40pt are level 0
const INDENT_LEVEL_1_MIN = 60; // Items with indent >= 60pt are level 1
// Docs uses 1.15 spacing when a paragraph style does not carry an override.
const GOOGLE_DOCS_DEFAULT_LINE_SPACING = 115;
// Docs applies this color automatically to ordinary links. Leaving it out of
// exported markup lets the browser or a consumer stylesheet own link theming.
const GOOGLE_DOCS_DEFAULT_LINK_COLOR = '#1155cc';
// List glyph types
const NUMBERED_GLYPH_TYPES = [
'DECIMAL', 'ALPHA', 'ROMAN',
'UPPER_ALPHA', 'UPPER_ROMAN',
'LOWER_ALPHA', 'LOWER_ROMAN'
];
// Basic alignment map for LTR paragraphs
const alignmentMapLTR = {
START: 'left',
CENTER: 'center',
END: 'right',
JUSTIFIED: 'justify'
};
// Border style map
const borderStyleMap = {
SOLID: 'solid',
DOTTED: 'dotted',
DASHED: 'dashed',
DOUBLE: 'double'
};
// Bullet style mappings
const BULLET_STYLE_MAP = {
'●': 'disc',
'○': 'circle',
'■': 'square',
'-': 'dash'
};
// Number style mappings
const NUMBER_STYLE_MAP = {
'DECIMAL': 'decimal',
'UPPER_ALPHA': 'upper-alpha',
'LOWER_ALPHA': 'lower-alpha',
'ALPHA': 'lower-alpha',
'UPPER_ROMAN': 'upper-roman',
'ROMAN': 'upper-roman',
'LOWER_ROMAN': 'lower-roman'
};
// ------------- HELPER FUNCTIONS -------------
/**
* Infer nesting level when not explicitly provided by the API.
* Uses indentation as a signal to determine the correct level.
*
* @param {object} bullet - The bullet object from the paragraph
* @param {object} paragraphStyle - The paragraph style containing indentStart
* @param {number} prevLevel - The previous item's nesting level
* @returns {number} The inferred nesting level
*/
function inferNestingLevel(bullet, paragraphStyle, prevLevel) {
if (bullet?.nestingLevel !== undefined) {
return bullet.nestingLevel;
}
const indentStart = paragraphStyle?.indentStart?.magnitude || 0;
// Use indentation heuristics
if (indentStart <= INDENT_LEVEL_0_MAX) {
return 0;
} else if (indentStart >= INDENT_LEVEL_1_MIN) {
return 1;
}
// Fallback: continue at previous level if in a list
return (prevLevel >= 0) ? prevLevel : 0;
}
/**
* Safely get a value with a default fallback.
*
* @param {*} value - The value to check
* @param {*} defaultValue - The default value to return if value is null/undefined
* @returns {*} The value or default
*/
function getOrDefault(value, defaultValue) {
return (value !== undefined && value !== null) ? value : defaultValue;
}
/**
* Detect the bullet style for an unordered list.
*
* @param {object} glyph - The glyph definition from list properties
* @returns {string} The bullet style name (disc, circle, square, dash)
*/
function detectBulletStyle(glyph) {
if (!glyph?.glyphSymbol) return 'disc';
return BULLET_STYLE_MAP[glyph.glyphSymbol] || 'disc';
}
/**
* Detect the numbering style for an ordered list.
*
* @param {object} glyph - The glyph definition from list properties
* @returns {string} The numbering style name (decimal, upper-alpha, etc.)
*/
function detectNumberStyle(glyph) {
if (!glyph?.glyphType) return 'decimal';
return NUMBER_STYLE_MAP[glyph.glyphType] || 'decimal';
}
/**
* Determine if a list is numbered based on glyph properties and item counts.
*
* @param {object} glyph - The glyph definition from list properties
* @param {string} listId - The list identifier
* @param {number} nestingLevel - The nesting level
* @param {object} listItemCounts - The item count map
* @returns {boolean} True if the list is numbered
*/
function isNumberedList(glyph, listId, nestingLevel, listItemCounts) {
// If glyphSymbol is present (●, ○, -, etc.) → bullet list
const isBullet = glyph?.glyphSymbol !== undefined;
if (isBullet) return false;
// If glyphType is explicitly a numbered type → numbered list
const explicitlyNumbered = NUMBERED_GLYPH_TYPES.includes(glyph?.glyphType);
if (explicitlyNumbered) return true;
// If GLYPH_TYPE_UNSPECIFIED: use item count heuristic
// Single-item lists → numbered (section markers)
// Multi-item lists → bullets
if (glyph?.glyphType === 'GLYPH_TYPE_UNSPECIFIED') {
const key = `${listId}:${nestingLevel}`;
const itemCount = listItemCounts?.[key] || 1;
return (itemCount === 1);
}
// Default to bullet list
return false;
}
async function exportDocToHTML(docId, outputDir, options = {}) {
try {
// Validate inputs
if (!docId || typeof docId !== 'string') {
throw new Error('Invalid document ID provided');
}
if (!outputDir || typeof outputDir !== 'string') {
throw new Error('Invalid output directory provided');
}
const stylesheetLinks = renderExternalStylesheetLinks(options.stylesheets);
const scriptTags = renderExternalScriptTags(options.scripts);
const headFragments = readHeadFiles(options.headFiles);
const htmlName = validateOutputEntryName(options.htmlName, 'index.html', 'HTML filename');
const imagesDirName = validateOutputEntryName(options.imagesDir, 'images', 'images directory');
// Create output directories
fs.mkdirSync(outputDir, { recursive: true });
const imagesDir = path.join(outputDir, imagesDirName);
fs.mkdirSync(imagesDir, { recursive: true });
// Auth & fetch doc
const authClient = await getAuthClient();
const docs = google.docs({ version: 'v1', auth: authClient });
const { data: doc } = await docs.documents.get(documentRequestParameters(docId));
if (!doc) {
throw new Error('Failed to fetch document from Google Docs API');
}
prepareTableOfContentsLinks(doc);
Object.defineProperty(doc, '___fontMetrics', {
value: await loadGoogleFontMetrics(collectFontFamilies(doc)),
enumerable: false
});
console.log(`Exporting doc: ${doc.title || 'Untitled'}`);
// Named styles for Title, Subtitle, Headings, etc.
const namedStylesMap = buildNamedStylesMap(doc);
// Container width from docStyle
const colInfo = computeDocContainerWidth(doc);
// Build global CSS
const globalCSS = generateGlobalCSS(doc, colInfo);
const usedFonts = new Set();
const styleRegistry = new StyleRegistry();
const documentLanguage = detectDocumentLanguage(doc);
let htmlLines = [];
// Basic HTML skeleton
htmlLines.push('<!DOCTYPE html>');
htmlLines.push(`<html lang="${documentLanguage.lang}" dir="${documentLanguage.direction}">`);
htmlLines.push('<head>');
htmlLines.push(' <meta charset="UTF-8">');
htmlLines.push(' <meta name="viewport" content="width=device-width">');
htmlLines.push(` <title>${escapeHtml(doc.title)}</title>`);
htmlLines.push(' <style>');
htmlLines.push(globalCSS);
htmlLines.push('/* Document-specific styles (deduplicated from the generated markup). */');
htmlLines.push('__DOCUMENT_STYLES__');
htmlLines.push(' </style>');
htmlLines.push(...stylesheetLinks);
htmlLines.push(...renderHeadFragments(headFragments, doc.title));
htmlLines.push('</head>');
htmlLines.push('<body>');
htmlLines.push('<main class="doc-content">');
// Pre-process positioned objects (fetch and prepare HTML, but don't insert yet)
const positionedObjectsHTML = new Map();
if (doc.positionedObjects) {
for (const [objId, posObj] of Object.entries(doc.positionedObjects)) {
try {
const props = posObj.positionedObjectProperties;
if (!props) continue;
const embedded = props.embeddedObject;
if (!embedded?.imageProperties) continue;
const { contentUri, cropProperties } = embedded.imageProperties;
if (!contentUri) continue;
// Fetch and save the image
const base64Data = await fetchAsBase64(contentUri, authClient);
if (!base64Data) {
console.warn(`Failed to fetch positioned image ${objId}`);
continue;
}
// Check for size information (prefer imageProperties.size, fallback to embedded.size)
const size = embedded.imageProperties.size || embedded.size;
let displayWidth, displayHeight;
if (size?.width?.magnitude && size?.height?.magnitude) {
const scaleX = embedded.transform?.scaleX || 1;
const scaleY = embedded.transform?.scaleY || 1;
displayWidth = Math.round(size.width.magnitude * 1.3333 * scaleX);
displayHeight = Math.round(size.height.magnitude * 1.3333 * scaleY);
}
const buffer = Buffer.from(base64Data, 'base64');
const { filePath, sourceWidth, sourceHeight } = await writeOptimizedImage(
buffer,
imagesDir,
`positioned_${objId}`,
{ displayWidth, displayHeight, maxDisplayWidth: colInfo, cropProperties }
);
const imgSrc = path.relative(outputDir, filePath);
// Build styles based on positioning properties and size
let style = `${responsiveImageSizeStyle(displayWidth, displayHeight)}display:block;`;
for (const [property, cssProperty] of [
['marginTop', 'margin-top'],
['marginRight', 'margin-right'],
['marginLeft', 'margin-left']
]) {
if (embedded[property]?.magnitude) {
style += `${cssProperty}:${ptToPx(embedded[property].magnitude)}px;`;
}
}
// Record the layout without inventing generic margins; Docs supplies exact ones.
const positioning = props.positioning;
if (positioning?.layout === 'WRAP_TEXT') {
style += 'shape-outside:margin-box;';
} else if (positioning?.layout === 'BREAK_BOTH' || positioning?.layout === 'BREAK_LEFT' || positioning?.layout === 'BREAK_RIGHT') {
style += 'margin-inline:auto;';
}
const alt = embedded.title || embedded.description || '';
const imageHTML = renderImage(imgSrc, alt, style, cropProperties,
{ displayWidth, displayHeight, sourceWidth, sourceHeight }, styleRegistry);
const offset = positioning?.leftOffset?.magnitude || 0;
const topOffset = positioning?.topOffset?.magnitude || 0;
let wrapperStyle = '';
if (offset) wrapperStyle += `margin-left:${ptToPx(offset)}px;`;
if (topOffset) wrapperStyle += `margin-top:${ptToPx(topOffset)}px;`;
const wrapperClass = joinClasses('positioned-image', styleRegistry.add('o', wrapperStyle));
positionedObjectsHTML.set(
objId,
`<figure class="${wrapperClass}">${imageHTML}</figure>`
);
} catch (error) {
console.error(`Error rendering positioned object ${objId}:`, error.message);
}
}
}
// Pre-process: count items per list per level to determine if single-item (numbered) or multi-item (bullets)
const listItemCounts = {};
const bodyContent = doc.body?.content || [];
doc.___footnoteNumbers = buildFootnoteNumberMap(bodyContent);
let prevLevel = -1;
for (const element of bodyContent) {
if (element.paragraph?.bullet) {
const bullet = element.paragraph.bullet;
const level = inferNestingLevel(bullet, element.paragraph.paragraphStyle, prevLevel);
const listId = bullet.listId;
const key = `${listId}:${level}`;
listItemCounts[key] = (listItemCounts[key] || 0) + 1;
prevLevel = level;
} else {
prevLevel = -1;
}
}
// Store counts in doc object for use by detectListChange
doc.___listItemCounts = listItemCounts;
let listStack = []; // Array of {type: 'ul'/'ol', level: 0/1/2...}
let prevNestingLevel = -1;
let prevListId = null; // Track previous listId to detect list changes
const insertedPositionedObjects = new Set();
for (const element of bodyContent) {
if (element.sectionBreak) {
if(prevNestingLevel>=0){ htmlLines.push('</li>'); prevNestingLevel=-1; prevListId=null; }
closeAllLists(listStack, htmlLines);
const sb = element.sectionBreak;
const sectionStyle = sb.sectionStyle;
// Handle column breaks
if(sectionStyle?.columnSeparatorStyle === 'BETWEEN_EACH_COLUMN'){
htmlLines.push('<div class="column-break"></div>');
} else if(sectionStyle?.columnProperties && sectionStyle.columnProperties.length > 1){
// Multi-column section
const colCount = sectionStyle.columnProperties.length;
const columnClass=styleRegistry.add('s', `column-count:${colCount};`);
htmlLines.push(`<div class="${joinClasses('multi-column', columnClass)}"></div>`);
} else {
htmlLines.push('<div class="section-break"></div>');
}
continue;
}
if (element.tableOfContents) {
if(prevNestingLevel>=0){ htmlLines.push('</li>'); prevNestingLevel=-1; prevListId=null; }
closeAllLists(listStack, htmlLines);
const tocHtml = await renderTableOfContents(
element.tableOfContents,
doc,
usedFonts,
authClient,
outputDir,
namedStylesMap,
styleRegistry
);
htmlLines.push(tocHtml);
continue;
}
if (element.paragraph) {
// Infer nesting level using helper function
const nestingLevel = element.paragraph.bullet
? inferNestingLevel(element.paragraph.bullet, element.paragraph.paragraphStyle, prevNestingLevel)
: -1;
// Pass previous nesting level and listId to detectListChange
element.paragraph.___prevNestingLevel = prevNestingLevel;
element.paragraph.___prevListId = prevListId;
// Close previous <li> if nesting level is changing
if (prevNestingLevel >= 0 && prevNestingLevel < nestingLevel) {
// Nesting deeper - don't close previous <li>, nested list will go inside it
} else if (prevNestingLevel >= 0 && listStack.length > 0) {
// Same level or going back up - close previous <li>
// When going back up, the nested list was already closed by handleListState
htmlLines.push('</li>');
}
try {
const { html, listChange } = await renderParagraph(
element.paragraph,
doc,
usedFonts,
listStack,
authClient,
outputDir,
imagesDir,
namedStylesMap,
styleRegistry
);
if (listChange) {
handleListState(listChange, listStack, htmlLines, styleRegistry);
}
if (listStack.length > 0) {
htmlLines.push(`<li>${html}`);
prevNestingLevel = nestingLevel;
prevListId = element.paragraph.bullet?.listId || null;
} else {
// Not in a list. The previous item was closed before rendering this
// paragraph; only reset the state here (emitting another </li> corrupts
// root lists when the list stack has just been closed).
if (prevNestingLevel >= 0) {
prevNestingLevel = -1;
}
prevListId = null;
htmlLines.push(html);
// Positioned objects are anchored to a paragraph in the Docs API. Emitting
// them directly after that paragraph preserves cover layouts and text flow.
for (const objectId of element.paragraph.positionedObjectIds || []) {
const objectHtml = positionedObjectsHTML.get(objectId);
if (objectHtml) {
htmlLines.push(objectHtml);
insertedPositionedObjects.add(objectId);
}
}
}
} catch (error) {
console.error('Error rendering paragraph:', error.message);
// Continue processing remaining elements
}
continue;
}
if (element.horizontalRule) {
if(prevNestingLevel>=0){ htmlLines.push('</li>'); prevNestingLevel=-1; prevListId=null; }
closeAllLists(listStack, htmlLines);
htmlLines.push('<hr>');
continue;
}
if (element.table) {
if(prevNestingLevel>=0){ htmlLines.push('</li>'); prevNestingLevel=-1; prevListId=null; }
closeAllLists(listStack, htmlLines);
const tableHtml = await renderTable(
element.table,
doc,
usedFonts,
authClient,
outputDir,
imagesDir,
namedStylesMap,
styleRegistry
);
htmlLines.push(tableHtml);
continue;
}
}
// Close final <li> if open
if (prevNestingLevel >= 0) {
htmlLines.push('</li>');
}
closeAllLists(listStack, htmlLines);
// If positioned objects weren't inserted yet (no title/subtitle in doc), insert at end
for (const [objectId, objectHtml] of positionedObjectsHTML) {
if (!insertedPositionedObjects.has(objectId)) htmlLines.push(objectHtml);
}
const footnotesHtml = await renderFootnotes(
doc,
usedFonts,
authClient,
outputDir,
imagesDir,
namedStylesMap,
styleRegistry
);
if (footnotesHtml) htmlLines.push(footnotesHtml);
htmlLines.push('</main>');
htmlLines.push(...scriptTags);
htmlLines.push('</body>');
htmlLines.push('</html>');
const documentStyles = styleRegistry.toCSS();
const stylePlaceholder = htmlLines.indexOf('__DOCUMENT_STYLES__');
if (stylePlaceholder >= 0) htmlLines[stylePlaceholder] = documentStyles;
// Insert Google Fonts if needed
const fontLink = buildGoogleFontsLink(Array.from(usedFonts));
if (fontLink) {
const idx = htmlLines.findIndex(l => l.includes('</title>'));
if (idx >= 0) {
htmlLines.splice(idx + 1, 0,
' <link rel="preconnect" href="https://fonts.googleapis.com">',
' <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>',
` <link rel="stylesheet" href="${fontLink}">`
);
}
}
// Write the generated HTML document.
const indexPath = path.join(outputDir, htmlName);
fs.writeFileSync(indexPath, htmlLines.join('\n'), 'utf8');
console.log(`HTML exported to: ${indexPath}`);
} catch (error) {
console.error('Export failed:', error.message);
if (error.code === 'ENOENT') {
console.error('File not found. Check your service account key file path.');
} else if (error.code === 'EACCES') {
console.error('Permission denied. Check file/directory permissions.');
} else if (error.response?.status === 404) {
console.error('Document not found. Check the document ID and access permissions.');
} else if (error.response?.status === 403) {
console.error('Access forbidden. Ensure the service account has access to the document.');
}
throw error;
}
}
function documentRequestParameters(documentId){
return {
documentId,
suggestionsViewMode:'PREVIEW_WITHOUT_SUGGESTIONS'
};
}
// -----------------------------------------------------
// Column width from doc documentStyle
// -----------------------------------------------------
function computeDocContainerWidth(doc) {
let containerPx = 800; // fallback
const ds = doc.documentStyle;
if (ds?.pageSize?.width?.magnitude) {
const pageW = ds.pageSize.width.magnitude;
const leftM = ds.marginLeft?.magnitude || 72;
const rightM = ds.marginRight?.magnitude || 72;
const usablePts = pageW - (leftM + rightM);
if (usablePts > 0) containerPx = ptToPx(usablePts);
}
// Pageless preview widens the page-derived text area by 66 CSS pixels. A
// paged document retains the exact printable width recorded by the API.
// Older fixtures predate documentMode, and preserve the established
// pageless behavior when the mode is unavailable.
if (ds?.documentFormat?.documentMode !== 'PAGES') containerPx += 66;
return containerPx;
}
// -----------------------------------------------------
// Global CSS with heading overrides
// -----------------------------------------------------
function generateGlobalCSS(doc, containerPx) {
const lines = [];
const documentStyle = doc.documentStyle || {};
const isPaged = documentStyle.documentFormat?.documentMode === 'PAGES';
const pagePadding = isPaged
? [
documentStyle.marginTop?.magnitude ?? 72,
documentStyle.marginRight?.magnitude ?? 72,
documentStyle.marginBottom?.magnitude ?? 72,
documentStyle.marginLeft?.magnitude ?? 72
].map(value => `${ptToPx(value)}px`).join(' ')
: '2em 1em';
const bodyBackground = isPaged ? '#f8f9fa' : 'transparent';
const pageBackground = isPaged
? '\n background:#fff;box-shadow:0 0 0 1px #dadce0;'
: '';
lines.push(`
/* Google Docs styles, rather than browser defaults, control block geometry. */
h1, h2, h3, h4, h5, h6, p, figure {
margin: 0;
font-size: 1em;
font-weight: normal;
}
*, *::before, *::after { box-sizing: border-box; }
body {
margin: 8px;
background: ${bodyBackground};
font-family: sans-serif;
/* Better font rendering for all scripts */
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-rendering: optimizeLegibility;
}
.doc-content {
box-sizing: content-box;
margin: 1em auto;
max-width: ${containerPx}px;
padding: ${pagePadding};${pageBackground}
}
p, h1, h2, h3, h4, h5, h6 {
white-space: pre-wrap;
overflow-wrap: break-word;
}
img {
display: inline-block;
max-width: 100%;
height: auto;
vertical-align: text-bottom;
}
sup {
vertical-align: baseline;
position: relative;
top: -0.4em;
line-height: 0;
font-size: 0.8em;
}
sub {
vertical-align: baseline;
position: relative;
top: 0.2em;
line-height: 0;
font-size: 0.8em;
}
.section-break {
page-break-before: always;
}
.column-break {
break-after: column;
}
.multi-column {
column-gap: 1em;
}
hr {
width: 100%;
border: 0;
border-top: 1px solid #ccc;
margin: 1em 0;
}
.subtitle { display: block; }
.positioned-image { width: 100%; }
.doc-table {
border-collapse: collapse;
margin: 0.5em 0;
width: 100%;
}
/* Equation styling */
.equation {
font-family: 'Cambria Math', 'Latin Modern Math', 'STIX Two Math', serif;
font-style: italic;
padding: 0 0.2em;
}
/* Page number placeholders */
.page-number, .page-count {
font-style: italic;
color: #666;
}
.page-break { break-after: page; }
.column-break-inline { break-after: column; }
.footnotes {
margin-top: 2em;
font-size: 0.9em;
}
.footnotes > ol { padding-inline-start: 2em; }
.footnote-backref { margin-inline-start: 0.35em; text-decoration: none; }
/* Right-to-left text improvements */
[dir="rtl"] {
text-align: right;
direction: rtl;
}
[dir="rtl"] ul, [dir="rtl"] ol {
padding-right: 2em;
padding-left: 0;
}
/* Better list spacing and nesting */
ul, ol {
margin: 0;
padding-left: 2em;
}
li {
margin: 0;
}
.doc-content li > p {
/* Docs list spacing belongs to the list line, not an extra block box. */
margin-block: 0;
}
ul ul, ol ol, ul ol, ol ul {
margin: 0;
}
/* Improved print styles */
@media print {
.doc-content {
max-width: none;
}
@page {
orphans: 2;
widows: 2;
}
}
`);
// If doc has pageSize => @page
if (doc.documentStyle?.pageSize?.width?.magnitude && doc.documentStyle?.pageSize?.height?.magnitude) {
const wIn = doc.documentStyle.pageSize.width.magnitude / 72;
const hIn = doc.documentStyle.pageSize.height.magnitude / 72;
const topM = (doc.documentStyle.marginTop?.magnitude||72)/72;
const rightM = (doc.documentStyle.marginRight?.magnitude||72)/72;
const botM = (doc.documentStyle.marginBottom?.magnitude||72)/72;
const leftM = (doc.documentStyle.marginLeft?.magnitude||72)/72;
lines.push(`
@page {
size: ${wIn}in ${hIn}in;
margin: ${topM}in ${rightM}in ${botM}in ${leftM}in;
}
`);
}
return lines.join('\n');
}
// -----------------------------------------------------
// Table of Contents (Indentation by heading level)
// -----------------------------------------------------
async function renderTableOfContents(
toc,
doc,
usedFonts,
authClient,
outputDir,
namedStylesMap,
styleRegistry
) {
let html = '<div class="doc-toc">\n';
if (toc.content) {
for (const c of toc.content) {
if (!c.paragraph) continue;
const { html:pHtml } = await renderParagraph(
c.paragraph,
doc,
usedFonts,
[],
authClient,
outputDir,
null,
namedStylesMap,
styleRegistry
);
html += `${pHtml}\n`;
}
}
html += '</div>\n';
return html;
}
function prepareTableOfContentsLinks(doc) {
const headingsByText = new Map();
for (const element of doc.body?.content || []) {
const paragraph = element.paragraph;
const namedStyle = paragraph?.paragraphStyle?.namedStyleType || '';
if (!namedStyle.startsWith('HEADING_')) continue;
const text = paragraphText(paragraph);
if (!text) continue;
const headings = headingsByText.get(text) || [];
headings.push({ element, paragraph });
headingsByText.set(text, headings);
}
let generatedId = 0;
for (const element of doc.body?.content || []) {
for (const tocElement of element.tableOfContents?.content || []) {
const paragraph = tocElement.paragraph;
if (!paragraph) continue;
const text = paragraphText(paragraph);
const target = headingsByText.get(text)?.shift();
if (!target) continue;
const linkRun = (paragraph.elements || []).find(item => item.textRun?.textStyle?.link);
if (!linkRun) continue;
const link = linkRun.textRun.textStyle.link;
if (link.url || link.bookmarkId || link.headingId) continue;
const headingId = `toc-${target.element.startIndex ?? ++generatedId}`;
target.paragraph.paragraphStyle ||= {};
target.paragraph.paragraphStyle.headingId = headingId;
link.headingId = headingId;
}
}
}
function paragraphText(paragraph) {
return (paragraph.elements || [])
.map(element => element.textRun?.content || '')
.join('')
.trim();
}
// -----------------------------------------------------
// Paragraph
// -----------------------------------------------------
async function renderParagraph(
paragraph,
doc,
usedFonts,
listStack,
authClient,
outputDir,
imagesDir,
namedStylesMap,
styleRegistry
) {
if (!paragraph) {
return { html: '', listChange: null };
}
const style = paragraph.paragraphStyle || {};
const namedType = style.namedStyleType || 'NORMAL_TEXT';
// Merge doc-based style
let mergedParaStyle={};
let mergedTextStyle={};
if(namedStylesMap[namedType]){
mergedParaStyle=deepCopy(namedStylesMap[namedType].paragraphStyle);
mergedTextStyle=deepCopy(namedStylesMap[namedType].textStyle);
}
deepMerge(mergedParaStyle, style);
deepMerge(mergedTextStyle, commonRunTypography(paragraph.elements || []));
// bullet logic
const isRTL=(mergedParaStyle.direction==='RIGHT_TO_LEFT');
let listChange=null;
if (paragraph.bullet) {
// prevNestingLevel and prevListId are passed from the main loop
const prevLevel = paragraph.___prevNestingLevel ?? -1;
const prevListId = paragraph.___prevListId;
listChange=detectListChange(paragraph,doc,listStack,isRTL,prevLevel,prevListId);
} else {
if(listStack.length>0){
// Exiting all lists
let actions = [];
for(let i = listStack.length - 1; i >= 0; i--){
actions.push(i === 0 ? 'endROOT' : 'endLIST');
}
listChange = actions.join('|');
}
}
// Title => <h1 class="title">, Subtitle => <h2 class="subtitle">, heading => <hX>, else <p>
let tag='p';
const paragraphClasses=[];
if(namedType==='TITLE'){
tag='h1';
paragraphClasses.push('title');
} else if(namedType==='SUBTITLE'){
tag='h2';
paragraphClasses.push('subtitle');
} else if(namedType.startsWith('HEADING_')){
const lv=parseInt(namedType.replace('HEADING_',''),10);
if(lv>=1 && lv<=6) tag=`h${lv}`;
}
let headingIdAttr='';
if(style.headingId){
headingIdAttr=` id="heading-${escapeHtml(style.headingId)}"`;
}
// alignment flipping
let align=mergedParaStyle.alignment;
if(isRTL && (align==='START'||align==='END')){
align=(align==='START')?'END':'START';
}
// doc-based lineSpacing => line-height
let inlineStyle='';
const metricTextStyle=deepCopy(mergedTextStyle);
const firstTextRun=(paragraph.elements || []).find(element => element.textRun?.content);
if(firstTextRun) deepMerge(metricTextStyle, firstTextRun.textRun.textStyle || {});
const baseFontFamily=metricTextStyle.weightedFontFamily?.fontFamily;
let lineHeightMultiplier=null;
const hasSoftBreak=(paragraph.elements || []).some(element =>
element.textRun?.content?.includes('\u000b')
);
const softBreakMetricKeys=new Set((paragraph.elements || [])
.filter(element => element.textRun?.content)
.map(element => {
const runStyle=deepCopy(mergedTextStyle);
deepMerge(runStyle, element.textRun.textStyle || {});
return runStyle.weightedFontFamily?.fontFamily || '';
}));
const hasMixedSoftBreakMetrics=hasSoftBreak && softBreakMetricKeys.size > 1;
const hasSoftBreakSizeOverride=hasSoftBreak && (paragraph.elements || []).some(element => {
if(!element.textRun?.content) return false;
const runStyle=deepCopy(mergedTextStyle);
deepMerge(runStyle, element.textRun.textStyle || {});
return JSON.stringify(runStyle.fontSize || null) !== JSON.stringify(mergedTextStyle.fontSize || null);
});
const needsIndependentSoftBreakLines=(
hasMixedSoftBreakMetrics ||
(hasSoftBreakSizeOverride && !mergedParaStyle.lineSpacing)
);
if(align && alignmentMapLTR[align]){
inlineStyle += `text-align:${alignmentMapLTR[align]};`;
}
if(mergedParaStyle.lineSpacing){
// Google Docs exposes lineSpacing as a percentage of the line box.
// A blank soft line uses the raw percentage strut. Size-overridden runs
// below receive an absolute line height based on the paragraph font.
lineHeightMultiplier=(hasSoftBreakSizeOverride && !hasMixedSoftBreakMetrics)
? mergedParaStyle.lineSpacing / 100
: docsLineHeight(baseFontFamily, mergedParaStyle.lineSpacing, doc.___fontMetrics);
inlineStyle += `line-height:${lineHeightMultiplier};`;
} else if(namedType === 'TITLE'){
lineHeightMultiplier=docsTitleLineHeight(baseFontFamily, doc.___fontMetrics);
inlineStyle += `line-height:${lineHeightMultiplier};`;
}
if(needsIndependentSoftBreakLines) inlineStyle += 'line-height:0;';
if(namedType === 'TITLE' && mergedParaStyle.lineSpacing > 100){
const fontPixels=ptToPx(metricTextStyle.fontSize?.magnitude || 24);
const extraLeading=Math.max(
0,
lineHeightMultiplier - docsTitleLineHeight(baseFontFamily, doc.___fontMetrics)
);
// CSS splits additional leading equally around glyphs. Docs titles retain
// their normal top-side leading and place the added spacing below them.
const topShift=Math.round(extraLeading * fontPixels / 2);
if(topShift) inlineStyle += `position:relative;top:-${topShift}px;`;
}
if(mergedParaStyle.spaceAbove?.magnitude){
inlineStyle += `margin-top:${ptToPx(mergedParaStyle.spaceAbove.magnitude)}px;`;
}
if(mergedParaStyle.spaceBelow?.magnitude){
const spaceBelowPx=ptToPx(mergedParaStyle.spaceBelow.magnitude);
const bodySpaceAbove=namedStylesMap.NORMAL_TEXT?.paragraphStyle?.spaceAbove?.magnitude;