修复了一些目录bug,但仍然有偏移,需要手动调整

This commit is contained in:
:NoBody: committed 2026-06-07 13:35:44 +08:00
1 parent ab5ca2485f
commit c886980a31
1 file changed
+70 -58
+70 -58
View File
@@ -412,11 +412,43 @@ export class IndexBuilder {
}
}
private async get_index_item_layouts(index_html: string) {
const { chromium } = await import("playwright");
const browser = await chromium.launch({
executablePath: resolveChromiumPath(),
headless: true,
args: ["--no-sandbox", "--disable-dev-shm-usage"],
});
const page = await browser.newPage();
try {
await page.setContent(index_html, { timeout: 120000 });
await page.emulateMedia({ media: "print" });
return await page.evaluate(() => {
const items = Array.from(
document.querySelectorAll<HTMLElement>("li.index-item"),
);
return items.map((item) => {
const rect = item.getBoundingClientRect();
return {
top: rect.top,
left: rect.left,
width: rect.width,
height: rect.height,
};
});
});
} finally {
await page.close();
await browser.close();
}
}
async combine_index_pdf_to_main_pdf(
index_pdf_path: string = "./tmps/index.pdf",
insert_index_after_page = 1,
) {
const combinedPdf = await PDFDocument.create();
const index_html = this.as_html_page();
const indexPdfBytes = await Deno.readFile(index_pdf_path);
const mainPdfBytes = await Deno.readFile(this.file_path);
@@ -446,10 +478,10 @@ export class IndexBuilder {
await this.add_index_link_annotations_to_pdf(
combinedPdf,
index_pdf_path,
this.get_sorted_index_entries(),
indexPages.length,
insert_index_after_page,
index_html,
);
const combinedPdfBytes = await combinedPdf.save();
@@ -476,6 +508,7 @@ export class IndexBuilder {
ctx: any,
rect: [number, number, number, number],
destPageRef: any,
destPageHeight: number,
) {
const annotation = ctx.obj({
Type: PDFName.of("Annot"),
@@ -495,7 +528,8 @@ export class IndexBuilder {
const destArray = annotation.lookup(PDFName.of("Dest"), PDFArray);
destArray.push(destPageRef);
destArray.push(PDFName.of("Fit"));
destArray.push(PDFName.of("FitH"));
destArray.push(PDFNumber.of(destPageHeight));
const annotationRef = ctx.register(annotation);
const annots = page.node.Annots();
@@ -506,27 +540,6 @@ export class IndexBuilder {
}
}
private async get_page_line_counts(pdf_path: string): Promise<number[]> {
const parser = new PDFParse({ url: pdf_path });
try {
const pdfText = await parser.getText();
const counts: number[] = [];
for (let page = 1; page <= pdfText.total; page++) {
const pageTextRaw = pdfText.getPageText(page);
const lines = pageTextRaw.split(/\r?\n/).map((l) => l.trim()).filter(
(l) => l.length > 0,
);
// The TOC title ("目录") occupies one line on the first page and should
// not be counted as an index item. Subtracting one keeps row assignment
// aligned with the actual clickable entries.
counts.push(Math.max(lines.length - 1, 0));
}
return counts;
} finally {
await parser.destroy();
}
}
private add_index_link_annotations(
pdfDoc: PDFDocument,
sorted_entries: Array<
@@ -535,13 +548,18 @@ export class IndexBuilder {
{ page: number; column_name: string },
]
>,
index_page_line_counts: number[],
index_item_layouts: Array<{
top: number;
left: number;
width: number;
height: number;
}>,
inserted_index_pages: number,
insert_index_after_page: number,
) {
if (
inserted_index_pages <= 0 || sorted_entries.length === 0 ||
index_page_line_counts.length === 0
index_item_layouts.length === 0
) {
return;
}
@@ -556,33 +574,24 @@ export class IndexBuilder {
}
const ctx = pdfDoc.context;
const { width, height } = indexPages[0].getSize();
const left = 36;
const right = 36;
const top = 110;
const rowHeight = 22;
const clickableHeight = 18;
const pageHeight = indexPages[0].getSize().height;
const pageWidth = indexPages[0].getSize().width;
const printableHeight = pageHeight - 40 - 40;
const marginTop = 40;
const marginBottom = 40;
let entryCursor = 0;
index_page_line_counts.forEach((lineCount: number, pageIndex: number) => {
const targetPage = indexPages[Math.min(pageIndex, indexPages.length - 1)];
const targetHeight = targetPage.getSize().height;
const usableRows = Math.max(
Math.min(
lineCount,
Math.floor((targetHeight - top - 60) / rowHeight),
),
0,
);
for (let rowIndex = 0; rowIndex < usableRows; rowIndex++) {
const entry = sorted_entries[entryCursor];
if (!entry) {
sorted_entries.forEach((entry, index) => {
const layout = index_item_layouts[index];
if (!layout) {
return;
}
const yTop = targetHeight - top - rowIndex * rowHeight;
const yBottom = yTop - clickableHeight;
const pageOffset = Math.floor(layout.top / printableHeight);
const targetPage = indexPages[Math.min(pageOffset, indexPages.length - 1)];
const localTop = layout.top - pageOffset * printableHeight;
const yTop = pageHeight - marginTop - localTop;
const yBottom = yTop - Math.max(layout.height, 12);
const xLeft = Math.max(layout.left - 12, 0);
const xRight = Math.min(layout.left + layout.width + 12, pageWidth);
const mappedPage = this.remap_page_after_index_insert(
entry[1].page,
inserted_index_pages,
@@ -594,20 +603,19 @@ export class IndexBuilder {
);
const destPage = pages[destPageIndex];
const destPageRef = (destPage as any).ref;
const destPageHeight = destPage.getSize().height;
this.add_link_annotation(
targetPage as any,
ctx,
[left, yBottom, width - right, yTop],
[xLeft, yBottom, xRight, yTop],
destPageRef,
destPageHeight,
);
entryCursor++;
}
});
}
private async add_index_link_annotations_to_pdf(
pdfDoc: PDFDocument,
index_pdf_path: string,
sorted_entries: Array<
[
string,
@@ -616,14 +624,13 @@ export class IndexBuilder {
>,
inserted_index_pages: number,
insert_index_after_page: number,
index_html: string,
) {
const index_page_line_counts = await this.get_page_line_counts(
index_pdf_path,
);
const index_item_layouts = await this.get_index_item_layouts(index_html);
this.add_index_link_annotations(
pdfDoc,
sorted_entries,
index_page_line_counts,
index_item_layouts,
inserted_index_pages,
insert_index_after_page,
);
@@ -664,9 +671,14 @@ export class IndexBuilder {
);
// deno-lint-ignore no-explicit-any
const pageRef = (pages[targetPageIndex] as any).ref;
const targetPageHeight = pages[targetPageIndex].getSize().height;
const dict = ctx.obj({
Title: PDFHexString.fromText(title),
Dest: [pageRef, PDFName.of("Fit")],
Dest: [
pageRef,
PDFName.of("FitH"),
PDFNumber.of(targetPageHeight),
],
});
const ref = ctx.register(dict);
itemNodes.push({ ref, dict });