View Issue Details

IDProjectCategoryView StatusLast Update
0018004ScribusImport / Exportpublic2026-10-29 17:09
Reporterbuttar Assigned To 
PrioritynormalSeverityfeatureReproducibilityN/A
Status newResolutionopen 
PlatformLinuxOSFedora WorkstationOS Version44
Product Version1.7.4.svn 
Target Version1.7.5.svn 
Summary0018004: [patch] Make PDF table of contents hyperlinked
Description- Currently, style-based ToC entries are not clickable in exported PDFs, requiring manually placed link annotations.
- This 3-patch series adds automatic internal navigation without changing document appearance or PDF export options.

## hpt1-document-reference-foundation-v1.04.patch

- Introduces persistent paragraph anchor IDs and link-target metadata, independent of experimental Notes/Marks.
- Adds SLA persistence and reference lifecycle handling for editing, duplication and copy/paste.
- Remaps paragraph identities during GUI/scripted page imports, preventing duplicate IDs and ambiguous destinations.

## hpt2-pdf-text-link-export-v1.03.patch

- Generates internal PDF link annotations from laid-out text geometry, including wrapped entries.
- Resolves destinations through deferred annotation writing; safely skips invalid or ambiguous targets.
- Preserves existing annotations, PDF/X restrictions and viewer zoom; adds 30 pt destination headroom.

## hpt3-clickable-style-based-toc-v1.00.patch

- Associates generated ToC entries with persistent source-heading anchors.
- Enables automatic clickable navigation, including after save/reopen and ToC regeneration.
- Requires one ToC regeneration for documents created before this feature.
Tags#please_test
Attached Files
hpt1-document-reference-foundation-v1.04.patch (33,617 bytes)   
Index: scribus/plugins/fileloader/scribus171format/scribus171format.cpp
===================================================================
--- scribus/plugins/fileloader/scribus171format/scribus171format.cpp	(revision 27881)
+++ scribus/plugins/fileloader/scribus171format/scribus171format.cpp	(working copy)
@@ -19,6 +19,7 @@
 #include <QRegularExpression>
 #include <QScopedPointer>
 #include <QStringView>
+#include <QUuid>
 
 #include "../../formatidlist.h"
 #include "commonstrings.h"
@@ -259,6 +260,9 @@
 
 bool Scribus171Format::loadElements(const QString& data, const QString& fileDir, int toLayer, double Xp_in, double Yp_in, bool loc)
 {
+	// Collect the imported stories first, then remap copied destination IDs
+	// together so references between copied objects still point to their copies.
+	QList<StoryText*> importedStories;
 	isNewFormat = false;
 	LayerToPaste = toLayer;
 	Xp = Xp_in;
@@ -434,6 +438,19 @@
 			if (!success)
 				break;
 			itemInfo.item->m_layerID = LayerToPaste;
+			if (itemInfo.item->isTextFrame() || itemInfo.item->isPathText())
+				importedStories.append(&itemInfo.item->itemText);
+			else if (itemInfo.item->isTable())
+			{
+				for (const auto& row : itemInfo.item->asTable()->cellRows())
+				{
+					for (const TableCell& cell : row)
+					{
+						if (cell.isValid() && cell.textFrame())
+							importedStories.append(&cell.textFrame()->itemText);
+					}
+				}
+			}
 			if (isNewFormat)
 			{
 				if (itemInfo.nextItem != -1)
@@ -731,6 +748,26 @@
 			}
 		}
 	}
+
+	// Selection imports are new destinations. Linked frames may share a story:
+	// the remapping is idempotent, and external destinations remain unchanged.
+	QHash<QString, QString> importedAnchorMap;
+	for (const StoryText* story : importedStories)
+	{
+		int p = story->indexOf(SpecialChars::PARSEP, 0);
+		while (p >= 0)
+		{
+			const QString oldId = story->paragraphAnchorId(p);
+			if (!oldId.isEmpty() && !importedAnchorMap.contains(oldId))
+				importedAnchorMap.insert(oldId, QUuid::createUuid().toString(QUuid::WithoutBraces));
+			p = story->indexOf(SpecialChars::PARSEP, p + 1);
+		}
+		const QString trailingId = story->paragraphAnchorId(story->length());
+		if (!trailingId.isEmpty() && !importedAnchorMap.contains(trailingId))
+			importedAnchorMap.insert(trailingId, QUuid::createUuid().toString(QUuid::WithoutBraces));
+	}
+	for (StoryText* story : importedStories)
+		story->remapParagraphReferences(importedAnchorMap);
 
 	while (groupStackP.count() > 0)
 	{
@@ -5806,12 +5843,16 @@
 			readParagraphStyle(doc, reader, newStyle);
 			story.setStyle(story.length() - 1, newStyle);
 			story.setCharStyle(story.length() - 1, 1, lastStyle->Style);
+			story.setParagraphAnchorId(story.length() - 1, tAtt.valueAsString("ParagraphAnchorId"));
+			story.setParagraphLinkTargetId(story.length() - 1, tAtt.valueAsString("ParagraphLinkTargetId"));
 		}
 		else if (tName == QLatin1String("trail"))
 		{
 			ParagraphStyle newStyle;
 			readParagraphStyle(doc, reader, newStyle);
 			story.setStyle(story.length(), newStyle);
+			story.setParagraphAnchorId(story.length(), tAtt.valueAsString("ParagraphAnchorId"));
+			story.setParagraphLinkTargetId(story.length(), tAtt.valueAsString("ParagraphLinkTargetId"));
 		}
 		else if (tName == QLatin1String("tab"))
 		{
Index: scribus/plugins/fileloader/scribus171format/scribus171format.h
===================================================================
--- scribus/plugins/fileloader/scribus171format/scribus171format.h	(revision 27881)
+++ scribus/plugins/fileloader/scribus171format/scribus171format.h	(working copy)
@@ -205,7 +205,7 @@
 		void writeTableStyles(ScXmlStreamWriter& docu, const QStringList& styleNames) const;
 		void writeCellStyles(ScXmlStreamWriter& docu) const;
 		void writeCellStyles(ScXmlStreamWriter& docu, const QStringList& styleNames) const;
-		void putPStyle(ScXmlStreamWriter& docu, const ParagraphStyle & style, const QString &nodeName) const;
+		void putPStyle(ScXmlStreamWriter& docu, const ParagraphStyle & style, const QString &nodeName, const QString& anchorId = QString(), const QString& targetId = QString()) const;
 		void putCStyle(ScXmlStreamWriter& docu, const CharStyle & style) const;
 		void putNamedCStyle(ScXmlStreamWriter& docu, const CharStyle & style) const;
 		void putTableStyle(ScXmlStreamWriter& docu, const TableStyle & style) const;
Index: scribus/plugins/fileloader/scribus171format/scribus171format_save.cpp
===================================================================
--- scribus/plugins/fileloader/scribus171format/scribus171format_save.cpp	(revision 27881)
+++ scribus/plugins/fileloader/scribus171format/scribus171format_save.cpp	(working copy)
@@ -810,13 +810,18 @@
 	}
 }
 
-void Scribus171Format::putPStyle(ScXmlStreamWriter & docu, const ParagraphStyle & style, const QString &nodeName) const
+void Scribus171Format::putPStyle(ScXmlStreamWriter & docu, const ParagraphStyle & style, const QString &nodeName, const QString& anchorId, const QString& targetId) const
 {
 	bool styleHasTabs = (!style.isInhTabValues() && !style.tabValues().isEmpty());
 	if (styleHasTabs)
 		docu.writeStartElement(nodeName);
 	else
 		docu.writeEmptyElement(nodeName);
+	// Per-paragraph metadata is never written on named ParagraphStyle records.
+	if (!anchorId.isEmpty())
+		docu.writeAttribute("ParagraphAnchorId", anchorId);
+	if (!targetId.isEmpty())
+		docu.writeAttribute("ParagraphLinkTargetId", targetId);
 	if (!style.name().isEmpty() )
 		docu.writeAttribute("Name", style.name());
 	if (!style.parent().isEmpty())
@@ -1917,8 +1922,8 @@
 				putCStyle(docu, lastStyle);
 			}
 		}
-		else if (ch == SpecialChars::PARSEP)	// stores also the paragraphstyle for preceding chars
-			putPStyle(docu, story.paragraphStyle(k), "para");
+		else if (ch == SpecialChars::PARSEP) // paragraph style and optional document reference
+			putPStyle(docu, story.paragraphStyle(k), "para", story.paragraphAnchorId(k), story.paragraphLinkTargetId(k));
 		else if (ch == SpecialChars::TAB)
 		{
 			docu.writeEmptyElement("tab");
@@ -1988,7 +1993,7 @@
 	// paragraphstyle for trailing chars
 	if (story.length() == 0 || story.text(story.length() - 1) != SpecialChars::PARSEP)
 	{
-		putPStyle(docu, story.paragraphStyle(story.length()), "trail");
+		putPStyle(docu, story.paragraphStyle(story.length()), "trail", story.paragraphAnchorId(story.length()), story.paragraphLinkTargetId(story.length()));
 	}
 }
 
Index: scribus/plugins/scriptplugin/cmdpage.cpp
===================================================================
--- scribus/plugins/scriptplugin/cmdpage.cpp	(revision 27881)
+++ scribus/plugins/scriptplugin/cmdpage.cpp	(working copy)
@@ -721,13 +721,16 @@
 	{
 		if (nrToImport > 0)
 		{
+			const int firstImportedItem = currentDoc->DocItems.count();
 			int counter = startPage + 1;
 			for (int i = 0; i < nrToImport; ++i)
 			{
 				ScCore->primaryMainWindow()->view->GotoPa(counter);
-				ScCore->primaryMainWindow()->loadPage(fromDoc, pageNs[i] - 1, false);
+				ScCore->primaryMainWindow()->loadPage(fromDoc, pageNs[i] - 1, false, QString(), false);
 				counter++;
 			}
+			if (currentDoc->DocItems.count() > firstImportedItem)
+				currentDoc->remapImportedParagraphReferences(currentDoc->DocItems.mid(firstImportedItem));
 		}
 	}
 
Index: scribus/scribus.cpp
===================================================================
--- scribus/scribus.cpp	(revision 27881)
+++ scribus/scribus.cpp	(working copy)
@@ -3327,14 +3327,19 @@
 		{
 			mainWindowProgressBar->reset();
 			mainWindowProgressBar->setMaximum(nrToImport);
+			const int firstImportedItem = doc->DocItems.count();
 			int counter = startPage;
 			for (int i = 0; i < nrToImport; ++i)
 			{
 				view->GotoPa(counter);
-				loadPage(dia->getFromDoc(), pageNs[i] - 1, false);
+				loadPage(dia->getFromDoc(), pageNs[i] - 1, false, QString(), false);
 				counter++;
 				mainWindowProgressBar->setValue(i + 1);
 			}
+			// Remap the entire batch together: links between imported pages must
+			// resolve to the imported headings, not the originals.
+			if (doc->DocItems.count() > firstImportedItem)
+				doc->remapImportedParagraphReferences(doc->DocItems.mid(firstImportedItem));
 			view->GotoPa(startPage);
 			mainWindowProgressBar->reset();
 			m_mainWindowStatusLabel->setText( tr("Import done"));
@@ -3353,7 +3358,7 @@
 	return ret;
 }
 
-bool ScribusMainWindow::loadPage(const QString& fileName, int Nr, bool Mpa, const QString& renamedPageName)
+bool ScribusMainWindow::loadPage(const QString& fileName, int Nr, bool Mpa, const QString& renamedPageName, bool remapReferences)
 {
 	if (fileName.isEmpty())
 		return false;
@@ -3373,6 +3378,8 @@
 		return false;
 	}
 	delete fl;
+	if (remapReferences && doc->Items->count() > oldItemsCount)
+		doc->remapImportedParagraphReferences(doc->Items->mid(oldItemsCount));
 	if (ScCore->haveCMS() && doc->cmsSettings().CMSinUse)
 	{
 		recalcColors();
Index: scribus/scribus.h
===================================================================
--- scribus/scribus.h	(revision 27881)
+++ scribus/scribus.h	(working copy)
@@ -356,7 +356,7 @@
 	bool slotFileNew();
 	void newFileFromTemplate();
 	bool slotPageImport();
-	bool loadPage(const QString& fileName, int Nr, bool Mpa, const QString& renamedPageName = QString());
+	bool loadPage(const QString& fileName, int Nr, bool Mpa, const QString& renamedPageName = QString(), bool remapReferences = true);
 	void gotoLayer(int l);
 	void slotGetContent();
 	void slotGetContent2(); // kk2006
Index: scribus/scribusdoc.cpp
===================================================================
--- scribus/scribusdoc.cpp	(revision 27881)
+++ scribus/scribusdoc.cpp	(working copy)
@@ -686,6 +686,28 @@
 			ret += embedded->getAllChildren();
 	}
 	return ret;
+}
+
+void ScribusDoc::remapImportedParagraphReferences(const QList<PageItem*>& importedItems)
+{
+	QList<StoryText*> stories;
+	for (PageItem* item : getAllItems(importedItems))
+	{
+		if (item->isTextFrame() || item->isPathText())
+			stories.append(&item->itemText);
+		else if (item->isTable())
+		{
+			for (const auto& row : item->asTable()->cellRows())
+			{
+				for (const TableCell& cell : row)
+				{
+					if (cell.isValid() && cell.textFrame())
+						stories.append(&cell.textFrame()->itemText);
+				}
+			}
+		}
+	}
+	StoryText::remapImportedParagraphReferences(stories);
 }
 
 QList<PageItem*> *ScribusDoc::parentGroup(PageItem* item, QList<PageItem*> *list)
Index: scribus/scribusdoc.h
===================================================================
--- scribus/scribusdoc.h	(revision 27881)
+++ scribus/scribusdoc.h	(working copy)
@@ -106,6 +106,8 @@
 		bool inAnEditMode() const;
 		bool inASpecialEditMode() const;
 		QList<PageItem*> getAllItems(const QList<PageItem*> &items) const;
+		// Reassign paragraph identities for a batch of imported page objects.
+		void remapImportedParagraphReferences(const QList<PageItem*>& importedItems);
 		QList<PageItem*> *parentGroup(PageItem* item, QList<PageItem*> *list);
 		/**
 	 * @param bindingDirection Defaults to 0 for all the one page temporary documents Scribus creates
Index: scribus/sctextstruct.h
===================================================================
--- scribus/sctextstruct.h	(revision 27881)
+++ scribus/sctextstruct.h	(working copy)
@@ -14,6 +14,7 @@
 #include "scribusapi.h"
 
 #include <QString>
+#include <memory>
 
 #include "scfonts.h"
 #include "style.h"
@@ -130,6 +131,14 @@
 	uint glyph { 0 };
 };
 
+// Reference metadata is owned by a paragraph instance, never a named style.
+// It does not occupy a character in the story or participate in text layout.
+struct ParagraphReference
+{
+	QString anchorId;
+	QString targetId;
+};
+
 class SCRIBUS_API ScText : public CharStyle
 {
 public:
@@ -142,6 +151,8 @@
 	{
 		if (other.parstyle)
 			parstyle = new ParagraphStyle(*other.parstyle);
+		if (other.paragraphReference)
+			paragraphReference = std::make_unique<ParagraphReference>(*other.paragraphReference);
 		if (other.mark)
 			setNewMark(other.mark);
 	}
@@ -149,6 +160,8 @@
 	~ScText() override;
 
 	ParagraphStyle* parstyle { nullptr }; // only for parseps
+	// Optional metadata for paragraph separators; trailing metadata is stored separately.
+	std::unique_ptr<ParagraphReference> paragraphReference;
 	int embedded { 0 };
 	Mark* mark { nullptr };
 	QChar ch;
Index: scribus/tests/testStoryText.cpp
===================================================================
--- scribus/tests/testStoryText.cpp	(revision 27881)
+++ scribus/tests/testStoryText.cpp	(working copy)
@@ -127,3 +127,184 @@
 	QCOMPARE(story.startOfRun(2), 5  + 26 + 1);
 	QCOMPARE(story.endOfRun(2), 11 + 26);
 }
+
+// Reference metadata belongs to paragraph instances, not shared styles.
+void TestStoryText::paragraphReferenceSplit()
+{
+	StoryText story;
+	story.insertChars(0, "Heading");
+	const QString id = story.ensureParagraphAnchorId(0);
+	QVERIFY(!id.isEmpty());
+	story.setParagraphLinkTargetId(0, "target-1");
+	story.insertChars(4, SpecialChars::PARSEP);
+	QCOMPARE(story.paragraphAnchorId(0), id);
+	QCOMPARE(story.paragraphLinkTargetId(0), QString("target-1"));
+	QVERIFY(story.paragraphAnchorId(5).isEmpty());
+	story.insertChars(0, SpecialChars::PARSEP);
+	QVERIFY(story.paragraphAnchorId(0).isEmpty());
+	QCOMPARE(story.paragraphAnchorId(1), id);
+}
+
+void TestStoryText::paragraphReferenceMerge()
+{
+	StoryText story;
+	story.insertChars(0, QString("First") + SpecialChars::PARSEP + "Second");
+	const QString firstId = story.ensureParagraphAnchorId(0);
+	story.ensureParagraphAnchorId(6);
+	story.removeChars(5, 1);
+	QCOMPARE(story.paragraphAnchorId(0), firstId);
+}
+
+void TestStoryText::paragraphReferenceDeletion()
+{
+	StoryText story;
+	story.insertChars(0, QString("Heading") + SpecialChars::PARSEP + "Body");
+	const QString deletedId = story.ensureParagraphAnchorId(0);
+	story.removeChars(0, 8); // heading + separator, not the body
+	QCOMPARE(story.text(0, story.length()), QString("Body"));
+	QVERIFY(story.paragraphAnchorId(0) != deletedId);
+	story.ensureParagraphAnchorId(0);
+	story.removeChars(0, 4);
+	QVERIFY(story.paragraphAnchorId(0).isEmpty());
+}
+
+void TestStoryText::paragraphReferencePaste()
+{
+	StoryText source;
+	source.insertChars(0, QString("Heading") + SpecialChars::PARSEP + "Body");
+	source.ensureParagraphAnchorId(0);
+	source.setParagraphLinkTargetId(0, "external-target");
+	StoryText pasted;
+	pasted.insert(0, source);
+	QVERIFY(pasted.paragraphAnchorId(0).isEmpty());
+	QCOMPARE(pasted.paragraphLinkTargetId(0), QString("external-target"));
+	StoryText snapshot = source.copy();
+	QCOMPARE(snapshot.paragraphAnchorId(0), source.paragraphAnchorId(0));
+}
+
+void TestStoryText::paragraphReferenceRemap()
+{
+	StoryText story;
+	story.insertChars(0, QString("Heading") + SpecialChars::PARSEP + "Link");
+	const QString original = story.ensureParagraphAnchorId(0);
+	const QString trailingOriginal = story.ensureParagraphAnchorId(8);
+	story.setParagraphLinkTargetId(0, "external-target");
+	story.setParagraphLinkTargetId(8, original);
+	QHash<QString, QString> map;
+	map.insert(original, "copy-id");
+	map.insert(trailingOriginal, "copy-trailing");
+	story.remapParagraphReferences(map);
+	QCOMPARE(story.paragraphAnchorId(0), QString("copy-id"));
+	QCOMPARE(story.paragraphAnchorId(8), QString("copy-trailing"));
+	QCOMPARE(story.paragraphLinkTargetId(0), QString("external-target"));
+	QCOMPARE(story.paragraphLinkTargetId(8), QString("copy-id"));
+}
+
+void TestStoryText::paragraphReferenceFirstIdentityOnJoin()
+{
+	StoryText story;
+	story.insertChars(0, QString("First") + SpecialChars::PARSEP + "Second");
+	const QString secondId = story.ensureParagraphAnchorId(6);
+	story.removeChars(5, 1);
+	QVERIFY(story.paragraphAnchorId(0).isEmpty());
+	QVERIFY(story.paragraphAnchorId(0) != secondId);
+}
+
+void TestStoryText::paragraphReferenceMultiParagraphDeletion()
+{
+	StoryText story;
+	story.insertChars(0, QString("First") + SpecialChars::PARSEP + "Middle" + SpecialChars::PARSEP + "Last");
+	const QString lastId = story.ensureParagraphAnchorId(13);
+	story.ensureParagraphAnchorId(0);
+	story.ensureParagraphAnchorId(6);
+	story.removeChars(0, 13);
+	QCOMPARE(story.text(0, story.length()), QString("Last"));
+	QCOMPARE(story.paragraphAnchorId(0), lastId);
+}
+
+void TestStoryText::paragraphReferenceCopyIsDeep()
+{
+	StoryText story;
+	story.insertChars(0, QString("One") + SpecialChars::PARSEP + "Two");
+	const QString original = story.ensureParagraphAnchorId(0);
+	StoryText snapshot = story.copy();
+	snapshot.setParagraphAnchorId(0, "independent");
+	QCOMPARE(story.paragraphAnchorId(0), original);
+	QCOMPARE(snapshot.paragraphAnchorId(0), QString("independent"));
+}
+
+void TestStoryText::paragraphReferenceTrailingPaste()
+{
+	StoryText source;
+	source.insertChars(0, "ToC entry");
+	source.setParagraphLinkTargetId(0, "destination");
+	StoryText pasted;
+	pasted.insert(0, source);
+	QCOMPARE(pasted.paragraphLinkTargetId(0), QString("destination"));
+	QVERIFY(pasted.paragraphAnchorId(0).isEmpty());
+}
+
+// Page imports copy entire stories, including persistent paragraph references.
+void TestStoryText::paragraphReferencePageImport()
+{
+	StoryText original;
+	original.insertChars(0, "Heading");
+	const QString originalId = original.ensureParagraphAnchorId(0);
+	StoryText copiedHeading = original.copy();
+	StoryText copiedToc;
+	copiedToc.insertChars(0, "Contents entry");
+	copiedToc.setParagraphLinkTargetId(0, originalId);
+	StoryText copiedExternal;
+	copiedExternal.insertChars(0, "External reference");
+	copiedExternal.setParagraphLinkTargetId(0, "external-target");
+	StoryText::remapImportedParagraphReferences({&copiedHeading, &copiedToc, &copiedExternal});
+	QVERIFY(!copiedHeading.paragraphAnchorId(0).isEmpty());
+	QVERIFY(copiedHeading.paragraphAnchorId(0) != originalId);
+	QCOMPARE(copiedToc.paragraphLinkTargetId(0), copiedHeading.paragraphAnchorId(0));
+	QCOMPARE(copiedExternal.paragraphLinkTargetId(0), QString("external-target"));
+	QCOMPARE(original.paragraphAnchorId(0), originalId);
+}
+
+void TestStoryText::paragraphReferenceRepeatedPageImport()
+{
+	StoryText original;
+	original.insertChars(0, "Heading");
+	const QString originalId = original.ensureParagraphAnchorId(0);
+	StoryText first = original.copy();
+	StoryText second = original.copy();
+	StoryText::remapImportedParagraphReferences({&first});
+	StoryText::remapImportedParagraphReferences({&second});
+	QVERIFY(first.paragraphAnchorId(0) != originalId);
+	QVERIFY(second.paragraphAnchorId(0) != originalId);
+	QVERIFY(first.paragraphAnchorId(0) != second.paragraphAnchorId(0));
+}
+
+void TestStoryText::paragraphReferenceAmbiguousPageImport()
+{
+	StoryText first;
+	first.insertChars(0, "Heading 1");
+	first.setParagraphAnchorId(0, "reused-id");
+	StoryText second;
+	second.insertChars(0, "Heading 2");
+	second.setParagraphAnchorId(0, "reused-id");
+	StoryText toc;
+	toc.insertChars(0, "Ambiguous ToC");
+	toc.setParagraphLinkTargetId(0, "reused-id");
+	StoryText::remapImportedParagraphReferences({&first, &second, &toc});
+	QVERIFY(!first.paragraphAnchorId(0).isEmpty());
+	QVERIFY(!second.paragraphAnchorId(0).isEmpty());
+	QVERIFY(first.paragraphAnchorId(0) != second.paragraphAnchorId(0));
+	QVERIFY(toc.paragraphLinkTargetId(0).isEmpty()); // Do not guess the destination.
+}
+
+void TestStoryText::paragraphReferenceSharedStoryImport()
+{
+	StoryText first;
+	first.insertChars(0, "Shared heading");
+	const QString originalId = first.ensureParagraphAnchorId(0);
+	StoryText linkedFrame(first); // Both wrappers point to the same story.
+	StoryText::remapImportedParagraphReferences({&first, &linkedFrame});
+	QVERIFY(!first.paragraphAnchorId(0).isEmpty());
+	QVERIFY(first.paragraphAnchorId(0) != originalId);
+	QCOMPARE(linkedFrame.paragraphAnchorId(0), first.paragraphAnchorId(0));
+}
Index: scribus/tests/testStoryText.h
===================================================================
--- scribus/tests/testStoryText.h	(revision 27881)
+++ scribus/tests/testStoryText.h	(working copy)
@@ -27,4 +27,17 @@
 	void removePars();
 	void applyCharStyle();
 	void removeCharStyle();
+	void paragraphReferenceSplit();
+	void paragraphReferenceMerge();
+	void paragraphReferenceDeletion();
+	void paragraphReferencePaste();
+	void paragraphReferenceRemap();
+	void paragraphReferenceFirstIdentityOnJoin();
+	void paragraphReferenceMultiParagraphDeletion();
+	void paragraphReferenceCopyIsDeep();
+	void paragraphReferenceTrailingPaste();
+	void paragraphReferencePageImport();
+	void paragraphReferenceRepeatedPageImport();
+	void paragraphReferenceAmbiguousPageImport();
+	void paragraphReferenceSharedStoryImport();
 };
Index: scribus/text/sctext_shared.cpp
===================================================================
--- scribus/text/sctext_shared.cpp	(revision 27881)
+++ scribus/text/sctext_shared.cpp	(working copy)
@@ -33,7 +33,8 @@
 	cursorPosition(other.cursorPosition),
 	selFirst(other.selFirst), selLast(other.selLast),
 	marksCount(other.marksCount), marksCountChanged(other.marksCountChanged),
-	trailingStyle(other.trailingStyle)
+	trailingStyle(other.trailingStyle),
+	trailingReference(other.trailingReference)
 {
 	pstyleContext.setDefaultStyle( &defaultStyle );
 	trailingStyle.setContext( &pstyleContext );
@@ -76,6 +77,7 @@
 	{
 		defaultStyle   = other.defaultStyle;
 		trailingStyle  = other.trailingStyle;
+		trailingReference = other.trailingReference;
 		pstyleContext  = other.pstyleContext;
 		pstyleContext.setDefaultStyle( &defaultStyle );
 		defaultStyle.setContext( other.defaultStyle.context() );
Index: scribus/text/sctext_shared.h
===================================================================
--- scribus/text/sctext_shared.h	(revision 27881)
+++ scribus/text/sctext_shared.h	(working copy)
@@ -11,6 +11,7 @@
 #include "style.h"
 #include "styles/charstyle.h"
 #include "styles/paragraphstyle.h"
+#include "sctextstruct.h"
 #include "styles/stylecontextproxy.h"
 
 
@@ -33,6 +34,7 @@
 	uint marksCount { 0 };
 	bool marksCountChanged { false };
 	ParagraphStyle trailingStyle;
+	ParagraphReference trailingReference;
 	CharStyle orphanedCharStyle;
 
 	void clear();
Index: scribus/text/storytext.cpp
===================================================================
--- scribus/text/storytext.cpp	(revision 27881)
+++ scribus/text/storytext.cpp	(working copy)
@@ -23,6 +23,8 @@
 
 //#include <QDebug>
 #include <unicode/brkiter.h>
+#include <QUuid>
+#include <QSet>
 
 //FIXME: this include must go to sctextstruct.h !
 #include <QList>
@@ -355,6 +357,7 @@
 	
 	d->defaultStyle.erase();
 	d->trailingStyle.erase();
+	d->trailingReference = ParagraphReference();
 
 	d->clear();
 	d->len = 0;
@@ -502,6 +505,9 @@
 			//#5845 : disable for now as it has nasty side effects when linking frames
 			//applyStyle(pos, otherDefault);
 			applyStyle(pos, other.paragraphStyle(i));
+			// A pasted paragraph may retain its outbound link, but must never
+			// claim the original paragraph's unique destination identity.
+			setParagraphLinkTargetId(pos, other.paragraphLinkTargetId(i));
 			cstyleStart = i+1;
 			++pos;
 		}
@@ -539,28 +545,205 @@
 			applyStyle(pos, other.paragraphStyle(otherEnd-1));
 		}
 	}
+	// Only a complete story inserted into an empty destination can keep
+	// the last paragraph's outbound link unambiguously. A paste into the
+	// middle of another paragraph must not replace that paragraph's link.
+	if (oldLen == 0 && oldPos == 0 && otherStart == 0 && otherEnd == other.length()
+		&& otherEnd > 0 && other.text(otherEnd - 1) != SpecialChars::PARSEP)
+		setParagraphLinkTargetId(length(), other.paragraphLinkTargetId(otherEnd));
 	if ((d->selLast >= d->selFirst) && (d->selFirst <= oldPos) && (oldPos <= d->selLast))
 		d->selLast += (length() - oldLen);
 	invalidate(pos, length());
 }
 
+
+ParagraphReference& StoryText::referenceForParagraph(int pos)
+{
+	assert(pos >= 0 && pos <= length());
+	for (int i = pos; i < length(); ++i)
+	{
+		ScText* ch = d->at(i);
+		if (ch->ch != SpecialChars::PARSEP)
+			continue;
+		if (!ch->paragraphReference)
+			ch->paragraphReference = std::make_unique<ParagraphReference>();
+		return *ch->paragraphReference;
+	}
+	return d->trailingReference;
+}
+
+const ParagraphReference& StoryText::referenceForParagraph(int pos) const
+{
+	assert(pos >= 0 && pos <= length());
+	for (int i = pos; i < length(); ++i)
+	{
+		const ScText* ch = d->at(i);
+		if (ch->ch == SpecialChars::PARSEP)
+		{
+			static const ParagraphReference emptyReference;
+			return ch->paragraphReference ? *ch->paragraphReference : emptyReference;
+		}
+	}
+	return d->trailingReference;
+}
+
+QString StoryText::paragraphAnchorId(int pos) const
+{
+	return referenceForParagraph(pos).anchorId;
+}
+
+QString StoryText::ensureParagraphAnchorId(int pos)
+{
+	const QString currentId = paragraphAnchorId(pos);
+	if (!currentId.isEmpty())
+		return currentId;
+	const QString newId = QUuid::createUuid().toString(QUuid::WithoutBraces);
+	setParagraphAnchorId(pos, newId);
+	return newId;
+}
+
+void StoryText::setParagraphAnchorId(int pos, const QString& id)
+{
+	if (!id.isEmpty() || !paragraphAnchorId(pos).isEmpty())
+		referenceForParagraph(pos).anchorId = id;
+}
+
+QString StoryText::paragraphLinkTargetId(int pos) const
+{
+	return referenceForParagraph(pos).targetId;
+}
+
+void StoryText::setParagraphLinkTargetId(int pos, const QString& id)
+{
+	if (!id.isEmpty() || !paragraphLinkTargetId(pos).isEmpty())
+		referenceForParagraph(pos).targetId = id;
+}
+
+void StoryText::remapImportedParagraphReferences(const QList<StoryText*>& importedStories)
+{
+	// Linked text frames can expose different StoryText wrappers for the same
+	// underlying story. Process each shared story only once.
+	QSet<ScText_Shared*> seen;
+	QList<StoryText*> stories;
+	for (StoryText* story : importedStories)
+	{
+		if (!story || seen.contains(story->d))
+			continue;
+		seen.insert(story->d);
+		stories.append(story);
+	}
+
+	QHash<QString, int> anchorCounts;
+	for (const StoryText* story : stories)
+	{
+		auto countAnchor = [&anchorCounts](const ParagraphReference& ref) {
+			if (!ref.anchorId.isEmpty())
+				++anchorCounts[ref.anchorId];
+		};
+		for (int i = 0; i < story->length(); ++i)
+		{
+			const ScText* ch = story->d->at(i);
+			if (ch->ch == SpecialChars::PARSEP && ch->paragraphReference)
+				countAnchor(*ch->paragraphReference);
+		}
+		countAnchor(story->d->trailingReference);
+	}
+	if (anchorCounts.isEmpty())
+		return;
+
+	QSet<QString> usedIds;
+	for (auto it = anchorCounts.cbegin(); it != anchorCounts.cend(); ++it)
+		usedIds.insert(it.key());
+	auto freshId = [&usedIds]() {
+		QString id;
+		do
+			id = QUuid::createUuid().toString(QUuid::WithoutBraces);
+		while (usedIds.contains(id));
+		usedIds.insert(id);
+		return id;
+	};
+
+	QHash<QString, QString> uniqueRemap;
+	QSet<QString> ambiguousIds;
+	for (auto it = anchorCounts.cbegin(); it != anchorCounts.cend(); ++it)
+	{
+		if (it.value() == 1)
+			uniqueRemap.insert(it.key(), freshId());
+		else
+			ambiguousIds.insert(it.key());
+	}
+
+	for (StoryText* story : stories)
+	{
+		story->remapParagraphReferences(uniqueRemap);
+		if (ambiguousIds.isEmpty())
+			continue;
+		// Multiple source paragraphs with one ID cannot be distinguished.
+		// Give each an independent anchor and suppress ambiguous imported links
+		// rather than sending readers to an arbitrary destination.
+		auto separateAmbiguous = [&ambiguousIds, &freshId](ParagraphReference& ref) {
+			if (ambiguousIds.contains(ref.anchorId))
+				ref.anchorId = freshId();
+			if (ambiguousIds.contains(ref.targetId))
+				ref.targetId.clear();
+		};
+		for (int i = 0; i < story->length(); ++i)
+		{
+			ScText* ch = story->d->at(i);
+			if (ch->ch == SpecialChars::PARSEP && ch->paragraphReference)
+				separateAmbiguous(*ch->paragraphReference);
+		}
+		separateAmbiguous(story->d->trailingReference);
+	}
+}
+
+void StoryText::remapParagraphReferences(const QHash<QString, QString>& anchorMap)
+{
+	if (anchorMap.isEmpty())
+		return;
+	// Only mapped identities are replaced; references outside the copied
+	// selection retain their original destinations.
+	auto remapId = [&anchorMap](QString& id) {
+		const auto replacement = anchorMap.constFind(id);
+		if (replacement != anchorMap.cend())
+			id = replacement.value();
+	};
+	for (int pos = 0; pos < length(); ++pos)
+	{
+		ScText* ch = d->at(pos);
+		if (ch->ch != SpecialChars::PARSEP || !ch->paragraphReference)
+			continue;
+		ParagraphReference& ref = *ch->paragraphReference;
+		remapId(ref.anchorId);
+		remapId(ref.targetId);
+	}
+	remapId(d->trailingReference.anchorId);
+	remapId(d->trailingReference.targetId);
+}
 
 /**
 	 need to remove the ParagraphStyle structure and replace all pointers
 	 to it...
  */
-void StoryText::removeParSep(int pos)
+void StoryText::removeParSep(int pos, bool preserveLeadingParagraph)
 {
 	ScText* it = item(pos);
+	// Joining paragraphs retains the leading paragraph's identity, including
+	// the absence of an identity. Removing a whole paragraph drops its reference.
+	if (preserveLeadingParagraph && pos > 0 && d->at(pos - 1)->ch != SpecialChars::PARSEP)
+	{
+		ParagraphReference& destination = referenceForParagraph(pos + 1);
+		destination = it->paragraphReference ? *it->paragraphReference : ParagraphReference();
+	}
+	it->paragraphReference.reset();
 	if (it->parstyle)
 	{
 		delete it->parstyle;
 		it->parstyle = nullptr;
 	}
-	// demote this parsep so the assert code in replaceCharStyleContextInParagraph()
-	// doesn't choke:
+	// Demote this separator before updating character-style contexts.
 	it->ch = QChar();
-	d->replaceCharStyleContextInParagraph(pos, paragraphStyle(pos+1).charStyleContext());
+	d->replaceCharStyleContextInParagraph(pos, paragraphStyle(pos + 1).charStyleContext());
 }
 
 /**
@@ -569,9 +752,20 @@
 void StoryText::insertParSep(int pos)
 {
 	ScText* it = item(pos);
+	// Inserting a separator within a paragraph keeps the identity with its
+	// leading text; at paragraph start it stays with the existing text.
+	if (pos > 0 && d->at(pos - 1)->ch != SpecialChars::PARSEP)
+	{
+		const ParagraphReference& oldReference = static_cast<const StoryText*>(this)->referenceForParagraph(pos + 1);
+		if (!oldReference.anchorId.isEmpty() || !oldReference.targetId.isEmpty())
+		{
+			it->paragraphReference = std::make_unique<ParagraphReference>(oldReference);
+			referenceForParagraph(pos + 1) = ParagraphReference();
+		}
+	}
 	if (!it->parstyle)
 	{
-		it->parstyle = new ParagraphStyle(paragraphStyle(pos+1));
+		it->parstyle = new ParagraphStyle(paragraphStyle(pos + 1));
 		it->parstyle->setContext( & d->pstyleContext);
 		// #7432 : when inserting a paragraph separator, apply/erase the trailing Style
 		if (pos >= signed(d->len - 1))
@@ -673,7 +867,14 @@
 	{
 		ScText *it = d->at(i);
 		if (it->ch == SpecialChars::PARSEP)
-			removeParSep(i);
+		{
+			// Only carry the preceding paragraph's identity if it has some
+			// text outside the deletion range. Otherwise its target is gone.
+			int paragraphStart = i;
+			while (paragraphStart > 0 && d->at(paragraphStart - 1)->ch != SpecialChars::PARSEP)
+				--paragraphStart;
+			removeParSep(i, paragraphStart < pos);
+		}
 		if ((it->ch == SpecialChars::OBJECT) && (it->mark != nullptr))
 			d->marksCount--;
 		d->takeAt(i);
@@ -693,6 +894,8 @@
 		d->marksCountChanged = true;
 
 	d->len = d->count();
+	if (d->len == 0)
+		d->trailingReference = ParagraphReference();
 	d->cursorPosition = qMin(d->cursorPosition, d->len);
 	if (d->selFirst > d->selLast)
 	{
Index: scribus/text/storytext.h
===================================================================
--- scribus/text/storytext.h	(revision 27881)
+++ scribus/text/storytext.h	(working copy)
@@ -29,6 +29,7 @@
 #include <QObject>
 #include <QString>
 #include <QList>
+#include <QHash>
 #include <unicode/uversion.h>
 
 #include "itextsource.h"
@@ -225,6 +226,20 @@
 	void getNamedResources(ResourceCollection& lists) const;
 	void replaceNamedResources(ResourceCollection& newNames);
 	
+	// Per-paragraph reference metadata. Positions identify a paragraph,
+	// including the trailing paragraph without a PARSEP. An empty ID means none.
+	QString paragraphAnchorId(int pos) const;
+	QString ensureParagraphAnchorId(int pos);
+	// Callers assigning explicit IDs must maintain document-wide uniqueness.
+	void setParagraphAnchorId(int pos, const QString& id);
+	QString paragraphLinkTargetId(int pos) const;
+	void setParagraphLinkTargetId(int pos, const QString& id);
+	// Remap IDs belonging to a copied story, leaving external targets intact.
+	void remapParagraphReferences(const QHash<QString, QString>& anchorMap);
+	// Assign independent IDs to imported stories and remap their internal links.
+	// Ambiguous targets in a source containing duplicate IDs cannot be preserved.
+	static void remapImportedParagraphReferences(const QList<StoryText*>& importedStories);
+
 	uint nrOfParagraphs() const;
 	int startOfParagraph() const;
 	int startOfParagraph(uint index) const;
@@ -326,6 +341,8 @@
 	static inline icu::BreakIterator* m_lineIterator { nullptr };
 
 
+	ParagraphReference& referenceForParagraph(int pos);
+	const ParagraphReference& referenceForParagraph(int pos) const;
 	ScText * item(int index);
 	const ScText * item(int index) const;
 	void fixSurrogateSelection();
@@ -335,7 +352,7 @@
 	
 	/// mark these runs as invalid, ie. need itemize and shaping
 	void invalidate(int firstRun, int lastRun);
-	void removeParSep(int pos);
+	void removeParSep(int pos, bool preserveLeadingParagraph = true);
 	void insertParSep(int pos);
 
 	// private:
PatchYes

Activities

buttar

2026-10-12 07:42

reporter   ~0054522

buttar

2026-10-13 09:55

reporter   ~0054525

The latest. I would stop here.
hpt2-pdf-text-link-export-v1.06.patch (14,391 bytes)   
Index: scribus/pdflib_core.cpp
===================================================================
--- scribus/pdflib_core.cpp	(revision 27881)
+++ scribus/pdflib_core.cpp	(working copy)
@@ -33,6 +33,7 @@
 #include <cmath>
 #include <cstdlib>
 #include <string>
+#include <utility>
 #ifdef HAVE_UNISTD_H
 #include <unistd.h>
 #endif
@@ -71,6 +72,7 @@
 #include "sccolorengine.h"
 #include "scfonts.h"
 #include "text/textlayoutpainter.h"
+#include "text/boxes.h"
 #include "fonts/cff.h"
 #include "fonts/sfnt.h"
 #include "scpage.h"
@@ -98,6 +100,12 @@
 using namespace std;
 using namespace TableUtils;
 
+namespace
+{
+// PDF destinations use points. Leave a small margin above text targets.
+constexpr double pdfNavigationHeadroomPt = 30.0;
+}
+
 #if defined(_WIN32)
 #undef GetObject
 #endif
@@ -961,6 +969,10 @@
 	BookMinUse = false;
 	UsedFontsP.clear();
 	UsedFontsF.clear();
+	m_textDestinations.clear();
+	m_ambiguousDestinations.clear();
+	m_textPageLinks.clear();
+	m_currentTextLinks.clear();
 	
 	writer.writeHeader(Options.Version);
 
@@ -3269,6 +3281,7 @@
 	ActPageP = pag;
 	Content.clear();
 	pageData.AObjects.clear();
+	m_currentTextLinks.clear();
 	pageData.radioButtonList.clear();
 	pageData.radioButtonGroups.clear();
 	if (Options.Thumbnails)
@@ -3520,6 +3533,17 @@
 		PutDoc(">>");
 		writer.endObj(Gobj);
 	}
+	// The link destinations may refer to later pages. Reserve an annotation
+	// array now and populate it when the full page tree has been written.
+	PdfId deferredAnnots = 0;
+	if (!m_currentTextLinks.isEmpty() && !PDF_IsPDFX())
+	{
+		deferredAnnots = writer.newObject();
+		TextPageLinks& pending = m_textPageLinks[ActPageP->pageNr()];
+		pending.annotationArray = deferredAnnots;
+		pending.existingAnnotations = pageData.AObjects;
+		pending.links = std::move(m_currentTextLinks);
+	}
 	PdfId pageObject = writer.newObject();
 	writer.startObj(pageObject);
 	PutDoc("<<\n/Type /Page\n/Parent " + Pdf::toObjRef(writer.PagesObj) + "\n");
@@ -3535,7 +3559,9 @@
 		PutDoc("/Group " + Pdf::toPdf(Gobj) + " 0 R\n");
 	if (Options.Thumbnails)
 		PutDoc("/Thumb " + Pdf::toPdf(pageData.Thumb) + " 0 R\n");
-	if (pageData.AObjects.count() != 0)
+	if (deferredAnnots != 0)
+		PutDoc("/Annots " + Pdf::toObjRef(deferredAnnots) + "\n");
+	else if (pageData.AObjects.count() != 0)
 	{
 		PutDoc("/Annots [ ");
 		for (int b = 0; b < pageData.AObjects.count(); ++b)
@@ -4604,10 +4630,14 @@
 					PdfId parentObject = radioButtonGroup.groupId;
 					PdfId kid = PDF_RadioButton(ite, parentObject, radioButtonGroup.groupName);
 					radioButtonGroup.kids.append(kid);
+					if (!pattern && pag->pageNameEmpty())
+						collectAnnotationParagraphDestinations(ite, pag);
 					break;
 				}
 				if (!PDF_Annotation(ite))
 					return false;
+				if (!pattern && pag->pageNameEmpty())
+					collectAnnotationParagraphDestinations(ite, pag);
 				break;
 			}
 			tmp += "q\n";
@@ -4663,7 +4693,12 @@
 			if (ite->imageFlippedV())
 				tmp += "1 0 0 -1 0 " + FToStr(-ite->height()) + " cm\n";
 			if (ite->itemText.length() != 0)
+			{
 				tmp += setTextSt(ite, PNr, pag);
+				// setTextSt() lays out the frame; capture only rendered lines.
+				if (!PDF_IsPDFX() && !pattern && pag->pageNameEmpty())
+					collectParagraphReferences(ite, pag);
+			}
 			tmp += "Q\n";
 			tmp += "Q\n";
 			if ((ite->lineColor() != CommonStrings::None) || (!ite->NamedLStyle.isEmpty()) || (!ite->strokePattern().isEmpty()) || (ite->GrTypeStroke > 0))
@@ -11245,12 +11280,241 @@
 	return true;
 }
 
+// The frame transform in page coordinates, including ancestor group scaling
+// and flips. Ordinary PageItem::getTransform() deliberately omits group flips.
+static QTransform textReferenceTransform(const PageItem* item)
+{
+	QList<const PageItem*> ancestry;
+	for (const PageItem* current = item; current; current = current->Parent)
+		ancestry.prepend(current);
+	QTransform transform;
+	for (int i = 0; i < ancestry.size(); ++i)
+	{
+		const PageItem* current = ancestry.at(i);
+		if (i == 0)
+			transform.translate(current->xPos(), current->yPos());
+		else
+			transform.translate(current->gXpos, current->gYpos);
+		transform.rotate(current->rotation());
+		if (current->isGroup() || current == item)
+		{
+			if (current->imageFlippedH())
+			{
+				transform.translate(current->width(), 0.0);
+				transform.scale(-1.0, 1.0);
+			}
+			if (current->imageFlippedV())
+			{
+				transform.translate(0.0, current->height());
+				transform.scale(1.0, -1.0);
+			}
+			if (current->isGroup() && current->groupWidth > 0 && current->groupHeight > 0)
+				transform.scale(current->width() / current->groupWidth, current->height() / current->groupHeight);
+		}
+	}
+	return transform;
+}
+
+void PDFLibCore::registerParagraphDestination(const QString& anchorId, int pageNumber, const QPointF& position, double pageTop)
+{
+	if (anchorId.isEmpty() || m_ambiguousDestinations.contains(anchorId))
+		return;
+	if (m_textDestinations.contains(anchorId))
+	{
+		m_textDestinations.remove(anchorId);
+		m_ambiguousDestinations.insert(anchorId);
+	}
+	else
+		m_textDestinations.insert(anchorId, TextDestination { pageNumber, position, pageTop });
+}
+
+// Annotation content is exported as an annotation object rather than page text.
+// Its paragraphs can still be targeted at the annotation's position on the page.
+void PDFLibCore::collectAnnotationParagraphDestinations(const PageItem* item, const ScPage* page)
+{
+	if (!item->isTextFrame() || item->asTextFrame()->isTableCellTextFrame())
+		return;
+
+	const StoryText& story = item->itemText;
+	const int first = qMax(0, item->firstInFrame());
+	const int last = qMin(story.length() - 1, item->lastInFrame());
+	if (first > last)
+		return;
+
+	const QRectF frame = textReferenceTransform(item).mapRect(QRectF(0.0, 0.0, item->width(), item->height()));
+	const QPointF origin = frame.topLeft();
+	double x = origin.x() - page->xOffset();
+	double y = page->height() - (origin.y() - page->yOffset());
+	if (Options.MirrorH && !page->masterPageNameEmpty())
+		x = page->width() - x;
+	if (Options.MirrorV && !page->masterPageNameEmpty())
+		y = page->height() - y;
+	const QPointF destination(x + bleedDisplacementX, y + bleedDisplacementY);
+	const double pageTop = page->height() + bleedDisplacementY;
+
+	for (int pos = first; pos <= last;)
+	{
+		const int paragraphStart = story.startOfParagraph(story.nrOfParagraph(pos));
+		if (paragraphStart >= first)
+			registerParagraphDestination(story.paragraphAnchorId(paragraphStart), page->pageNr(), destination, pageTop);
+		const int next = story.startOfNextParagraph(pos);
+		if (next <= pos)
+			break;
+		pos = next;
+	}
+}
+
+void PDFLibCore::collectParagraphReferences(const PageItem* item, const ScPage* page)
+{
+	if (!item->isTextFrame() || item->asTextFrame()->isTableCellTextFrame())
+		return;
+	const StoryText& story = item->itemText;
+	const Box* root = item->textLayout.box();
+	if (!root || story.length() == 0)
+		return;
+
+	// Linked frames share the full StoryText. Inspect only paragraphs that
+	// intersect this frame, rather than rescanning the story for each frame.
+	const int first = qMax(0, item->firstInFrame());
+	const int last = qMin(story.length() - 1, item->lastInFrame());
+	if (first > last)
+		return;
+	bool hasReference = false;
+	for (int pos = first; pos <= last;)
+	{
+		if (!story.paragraphAnchorId(pos).isEmpty() || !story.paragraphLinkTargetId(pos).isEmpty())
+		{
+			hasReference = true;
+			break;
+		}
+		const int separator = story.indexOf(SpecialChars::PARSEP, pos);
+		if (separator < 0 || separator >= last)
+			break;
+		pos = separator + 1;
+	}
+	if (!hasReference)
+		return;
+
+	const QTransform frameTransform = textReferenceTransform(item);
+	const QRectF frameBounds(0.0, 0.0, item->width(), item->height());
+	const int pageNumber = page->pageNr();
+	auto toPdfPoint = [this, page, &frameTransform](const QPointF& localPoint) {
+		const QPointF docPoint = frameTransform.map(localPoint);
+		double x = docPoint.x() - page->xOffset();
+		double y = page->height() - (docPoint.y() - page->yOffset());
+		if (Options.MirrorH && !page->masterPageNameEmpty())
+			x = page->width() - x;
+		if (Options.MirrorV && !page->masterPageNameEmpty())
+			y = page->height() - y;
+		return QPointF(x + bleedDisplacementX, y + bleedDisplacementY);
+	};
+	for (const Box* column : root->boxes())
+	{
+		for (const Box* box : column->boxes())
+		{
+			const LineBox* line = dynamic_cast<const LineBox*>(box);
+			if (!line)
+				continue;
+			const int lineEnd = qMin(story.length(), line->lastChar() + 1);
+			int begin = qMax(0, line->firstChar());
+			while (begin < lineEnd)
+			{
+				const int separator = story.indexOf(SpecialChars::PARSEP, begin);
+				const int paraEnd = separator >= 0 ? separator : story.length();
+				const int end = qMin(paraEnd, lineEnd);
+				const QString anchorId = story.paragraphAnchorId(begin);
+				const QString targetId = story.paragraphLinkTargetId(begin);
+				if (!anchorId.isEmpty() || !targetId.isEmpty())
+				{
+					QRectF bounds;
+					bool hasGlyph = false;
+					for (const Box* glyph : line->boxes())
+					{
+						if (glyph->lastChar() < begin || glyph->firstChar() >= end || glyph->width() <= 0.0)
+							continue;
+						const QRectF glyphBounds(root->x() + column->x() + line->x() + glyph->x(),
+							root->y() + column->y() + line->y(), glyph->width(), line->height());
+						bounds = hasGlyph ? bounds.united(glyphBounds) : glyphBounds;
+						hasGlyph = true;
+					}
+					if (hasGlyph)
+					{
+						bounds = bounds.intersected(frameBounds);
+						if (bounds.width() > 0 && bounds.height() > 0)
+						{
+							QPolygonF quad;
+							quad << toPdfPoint(bounds.topLeft()) << toPdfPoint(bounds.topRight())
+							     << toPdfPoint(bounds.bottomLeft()) << toPdfPoint(bounds.bottomRight());
+							if (begin == 0 || story.text(begin - 1) == SpecialChars::PARSEP)
+								registerParagraphDestination(anchorId, pageNumber, quad.at(0), page->height() + bleedDisplacementY);
+							if (!targetId.isEmpty())
+								m_currentTextLinks.append(TextLink { targetId, quad });
+						}
+					}
+				}
+				// A paragraph separator may itself terminate this line.
+				begin = separator >= 0 && separator < lineEnd ? separator + 1 : lineEnd;
+			}
+		}
+	}
+}
+
+void PDFLibCore::PDF_End_TextLinks()
+{
+	// /XYZ uses PDF points, with Y increasing upwards. Place the heading a
+	// little below the viewer's top edge, but never above the page trim edge.
+	// A null zoom operand leaves the viewer's current magnification unchanged.
+	for (auto pageIt = m_textPageLinks.cbegin(); pageIt != m_textPageLinks.cend(); ++pageIt)
+	{
+		const TextPageLinks& pageLinks = pageIt.value();
+		QList<PdfId> annotations = pageLinks.existingAnnotations;
+		for (const TextLink& link : pageLinks.links)
+		{
+			const auto destination = m_textDestinations.constFind(link.targetId);
+			if (destination == m_textDestinations.cend())
+				continue;
+			const auto destPage = PageTree.KidsMap.constFind(destination->pageNumber);
+			if (destPage == PageTree.KidsMap.cend() || link.quad.size() != 4)
+				continue;
+			const QRectF rect = link.quad.boundingRect();
+			if (rect.width() <= 0 || rect.height() <= 0)
+				continue;
+			const PdfId annotation = writer.newObject();
+			writer.startObj(annotation);
+			PutDoc("<< /Type /Annot /Subtype /Link\n/Rect ["
+			       + FToStr(rect.left()) + " " + FToStr(rect.top()) + " "
+			       + FToStr(rect.right()) + " " + FToStr(rect.bottom()) + "]\n");
+			PutDoc("/Border [0 0 0]\n/F 0\n"); // No visible border, not printable
+			if (Options.Version >= PDFVersion::PDF_16)
+			{
+				PutDoc("/QuadPoints [");
+				for (const QPointF& point : link.quad)
+					PutDoc(FToStr(point.x()) + " " + FToStr(point.y()) + " ");
+				PutDoc("]\n");
+			}
+			const double viewTop = qMin(destination->position.y() + pdfNavigationHeadroomPt, destination->pageTop);
+			PutDoc("/Dest [" + Pdf::toObjRef(destPage.value()) + " /XYZ "
+			       + FToStr(destination->position.x()) + " "
+			       + FToStr(viewTop) + " null]\n>>");
+			writer.endObj(annotation);
+			annotations.append(annotation);
+		}
+		writer.startObj(pageLinks.annotationArray);
+		PutDoc("[ ");
+		for (const PdfId annotation : annotations)
+			PutDoc(Pdf::toObjRef(annotation) + " ");
+		PutDoc("]");
+		writer.endObj(pageLinks.annotationArray);
+	}
+}
+
 bool PDFLibCore::PDF_End_Doc(const QString& outputProfilePath)
 {
 	PDF_End_Bookmarks();
 	PDF_End_Resources();
 	PDF_End_Outlines();
 	PDF_End_PageTree();
+	PDF_End_TextLinks();
 	PDF_End_NamedDests();
 	PDF_End_FormObjects();
 	PDF_End_JavaScripts();
Index: scribus/pdflib_core.h
===================================================================
--- scribus/pdflib_core.h	(revision 27881)
+++ scribus/pdflib_core.h	(working copy)
@@ -9,6 +9,11 @@
 #define PDFLIBCORE_H
 
 #include <QFile>
+#include <QHash>
+#include <QPointF>
+#include <QPolygonF>
+#include <QRectF>
+#include <QSet>
 #include <QDataStream>
 #include <QPixmap>
 #include <QList>
@@ -175,6 +180,10 @@
 	void PDF_End_Outlines();
 	void PDF_End_PageTree();
 	void PDF_End_NamedDests();
+	void collectParagraphReferences(const PageItem* item, const ScPage* page);
+	void collectAnnotationParagraphDestinations(const PageItem* item, const ScPage* page);
+	void registerParagraphDestination(const QString& anchorId, int pageNumber, const QPointF& position, double pageTop);
+	void PDF_End_TextLinks();
 	void PDF_End_FormObjects();
 	void PDF_End_JavaScripts();
 	void PDF_End_Articles();
@@ -284,6 +293,29 @@
 	void generateXMP(const QString& timeStamp);
 //	int bytesWritten() { return Spool.pos(); }
 
+	// Document references are resolved only after the exported PDF pages exist.
+	struct TextDestination
+	{
+		int pageNumber { -1 };
+		QPointF position;  // PDF user-space coordinates
+		double pageTop { 0.0 }; // Top trim edge in PDF user-space coordinates
+	};
+	struct TextLink
+	{
+		QString targetId;
+		QPolygonF quad;  // PDF user-space coordinates, TL, TR, BL, BR
+	};
+	struct TextPageLinks
+	{
+		PdfId annotationArray { 0 };
+		QList<PdfId> existingAnnotations;
+		QList<TextLink> links;
+	};
+	QHash<QString, TextDestination> m_textDestinations;
+	QSet<QString> m_ambiguousDestinations;
+	QMap<int, TextPageLinks> m_textPageLinks;
+	QList<TextLink> m_currentTextLinks;
+
 	PdfCatalog Catalog;
 	PdfPageData pageData;
 	PdfPageTree PageTree;
hpt3-clickable-style-based-toc-v1.00.patch (2,330 bytes)   
Index: scribus/tocgenerator.cpp
===================================================================
--- scribus/tocgenerator.cpp	(revision 27881)
+++ scribus/tocgenerator.cpp	(working copy)
@@ -173,6 +173,7 @@
 		QString entryText;
 		QString entryStyle;
 		TOCPageLocation entryPageLocation;
+		QString destinationId;
 	};
 
 	// Collect all text frames including those placed inside groups;
@@ -303,6 +304,9 @@
 						ted.entryText = paraText;
 						ted.entryStyle = (*tocEntryIterator).styleForText;
 						ted.entryPageLocation = (*tocEntryIterator).pageLocation;
+						// Resolve the heading by paragraph identity, not by its text or page number.
+						// Reuse the ID when this ToC is generated again or the heading moves.
+						ted.destinationId = item->itemText.ensureParagraphAnchorId(para_start);
 						tocMap.insert(key, ted);
 					}
 				}
@@ -315,25 +319,32 @@
 			QString tocPage(tocIt.key().section(',', 2, 2).trimmed());
 			QString tocLine;
 			//Start with text or numbers
-			TOCPageLocation tpl = tocMap.value(tocIt.key()).entryPageLocation;
+			const TOCEntryData& entry = tocIt.value();
+			TOCPageLocation tpl = entry.entryPageLocation;
 			if (tpl == End || tpl == NotShown)
-				tocLine = tocMap.value(tocIt.key()).entryText;
+				tocLine = entry.entryText;
 			if (tpl == Beginning && oldTocPage != tocPage)
 				tocLine = tocPage;
 			//Add in the tab for the leaders
 			tocLine += "\t";
 			//End with text or numbers
 			if (tpl == Beginning)
-				tocLine += tocMap.value(tocIt.key()).entryText;
+				tocLine += entry.entryText;
 			if (tpl == End && oldTocPage != tocPage)
 				tocLine += tocPage;
 			tocLine += "\n";
 
 			const gtFrameStyle *fstyle = writer.getDefaultStyle();
 			gtParagraphStyle *pstyle = new gtParagraphStyle(*fstyle);
-			pstyle->setName(tocMap.value(tocIt.key()).entryStyle);
+			pstyle->setName(entry.entryStyle);
 			writer.setParagraphStyle(pstyle);
+			const int entryStart = tocFrame->itemText.length();
 			writer.append(tocLine);
+			// The generated entry is a paragraph: its link follows its text across
+			// line wraps, linked frames and SLA save/reopen. No PDF-only objects are
+			// inserted into the story.
+			if (tocFrame->itemText.length() > entryStart)
+				tocFrame->itemText.setParagraphLinkTargetId(entryStart, entry.destinationId);
 		}
 	}
 }

Issue History

Date Modified Username Field Change
2026-10-12 07:00 buttar New Issue
2026-10-12 07:00 buttar Tag Attached: #please_test
2026-10-12 07:00 buttar File Added: hpt1-document-reference-foundation-v1.04.patch
2026-10-12 07:42 buttar Note Added: 0054522
2026-10-12 07:42 buttar File Added: hpt2-pdf-text-link-export-v1.03.patch
2026-10-12 07:42 buttar File Added: hpt3-clickable-style-based-toc-v1.00.patch
2026-10-13 09:55 buttar File Deleted: hpt2-pdf-text-link-export-v1.03.patch
2026-10-13 09:55 buttar File Deleted: hpt3-clickable-style-based-toc-v1.00.patch
2026-10-13 09:55 buttar Note Added: 0054525
2026-10-13 09:55 buttar File Added: hpt2-pdf-text-link-export-v1.06.patch
2026-10-13 09:55 buttar File Added: hpt3-clickable-style-based-toc-v1.00.patch
2026-10-17 20:12 cbradney Target Version => 1.8 Milestone
2026-10-17 20:12 cbradney Patch => No
2026-10-18 08:33 cbradney Patch No => Yes
2026-10-29 17:09 cbradney Target Version 1.8 Milestone => 1.7.5.svn