Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions core/fpdfapi/edit/BUILD.gn
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,6 +21,8 @@ source_set("edit") {
"cpdf_pageorganizer.h",
"cpdf_stringarchivestream.cpp",
"cpdf_stringarchivestream.h",
"cpdf_text_redactor.cpp",
"cpdf_text_redactor.h",
]
configs += [
"../../../:pdfium_strict_config",
Expand Down
295 changes: 248 additions & 47 deletions core/fpdfapi/edit/cpdf_pagecontentgenerator.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -30,6 +30,9 @@
#include "core/fpdfapi/page/cpdf_path.h"
#include "core/fpdfapi/page/cpdf_pathobject.h"
#include "core/fpdfapi/page/cpdf_textobject.h"
#include "core/fpdfapi/page/cpdf_color.h"
#include "core/fpdfapi/page/cpdf_colorspace.h"
#include "core/fpdfapi/page/cpdf_iccprofile.h"
#include "core/fpdfapi/parser/cpdf_array.h"
#include "core/fpdfapi/parser/cpdf_dictionary.h"
#include "core/fpdfapi/parser/cpdf_document.h"
Expand All@@ -53,27 +56,56 @@ namespace {
// - ColorSpace
// - Pattern
// - Shading
constexpr const char* kResourceKeys[] = {"ExtGState", "Font", "XObject"};
constexpr const char* kResourceKeys[] = {"ExtGState", "Font", "XObject", "ColorSpace"};

// Key: The resource type.
// Value: The resource names of a given type.
using ResourcesMap = std::map<ByteString, std::set<ByteString>>;

// Returns whether it wrote to `buf` or not.
bool WriteColorToStream(fxcrt::ostringstream& buf, const CPDF_Color* color) {
if (!color || (!color->IsColorSpaceRGB() && !color->IsColorSpaceGray())) {
return false;
bool TextObjectNeedsTJ(const CPDF_TextObject* obj) {
// We don’t have a public accessor for char_codes_, but we can reuse CountItems()
// and GetItemInfo(i). GetItemInfo() gives us char_code_ and (for vert writing)
// origin_. We only need to see if any item has the sentinel.
for (size_t i = 0, n = obj->CountItems(); i < n; ++i) {
auto it = obj->GetItemInfo(i);
if (it.char_code_ == CPDF_Font::kInvalidCharCode)
return true;
}
return false;
}

std::optional<FX_RGB_STRUCT<float>> colors = color->GetRGB();
if (!colors.has_value()) {
return false;
void WriteTextAsTJ(fxcrt::ostringstream& buf,
CPDF_TextObject* obj,
CPDF_Font* font) {
buf << "[ ";
ByteString hexChunk;

for (size_t i = 0, n = obj->CountItems(); i < n; ++i) {
CPDF_TextObject::Item it = obj->GetItemInfo(i);

if (it.char_code_ == CPDF_Font::kInvalidCharCode) {
if (!hexChunk.IsEmpty()) {
buf << PDF_HexEncodeString(hexChunk.AsStringView()) << " ";
hexChunk.clear();
}
float thousandths = 0.0f;
if (obj->GetSeparatorAdjustment(i, &thousandths)) {
// TJ numbers are interpreted as “subtract this from the text position”,
// which matches how CalcPositionDataInternal() used the stored value:
// curpos -= (thousandths * fontSize)/1000. So we emit the value as-is.
WriteFloat(buf, thousandths);
buf << " ";
}
continue;
}

font->AppendChar(&hexChunk, it.char_code_);
}

WriteFloat(buf, colors.value().red) << " ";
WriteFloat(buf, colors.value().green) << " ";
WriteFloat(buf, colors.value().blue);
return true;
if (!hexChunk.IsEmpty()) {
buf << PDF_HexEncodeString(hexChunk.AsStringView()) << " ";
}
buf << "] TJ";
}

// Balances the "q" operator ProcessGraphics() emitted.
Expand DownExpand Up@@ -103,6 +135,11 @@ void RecordPageObjectResourceUsage(const CPDF_PageObject* page_object,
CHECK(!name.IsEmpty());
seen_resources["ExtGState"].insert(name);
}
const CPDF_ColorState& cs = page_object->color_state();
if (!cs.GetFillColorSpaceResName().IsEmpty())
seen_resources["ColorSpace"].insert(cs.GetFillColorSpaceResName());
if (!cs.GetStrokeColorSpaceResName().IsEmpty())
seen_resources["ColorSpace"].insert(cs.GetStrokeColorSpaceResName());
}

CPDF_PageObjectHolder::RemovedResourceMap RemoveUnusedResources(
Expand DownExpand Up@@ -357,6 +394,25 @@ CPDF_PageContentGenerator::GenerateModifiedStreams() {
all_dirty_streams.insert(marked_dirty_streams.begin(),
marked_dirty_streams.end());

// --- embedpdf: if anything is dirty, regenerate *all* page content streams.
// Rationale: CTM / graphics-state handoff between streams means rewriting
// only a subset can leave the concatenated effect inconsistent.
if (!all_dirty_streams.empty()) {
int32_t last_index = -1;
if (RetainPtr<const CPDF_Object> contents =
obj_holder_->GetDict()->GetObjectFor(pdfium::page_object::kContents)) {
if (const CPDF_Array* arr = contents->AsArray()) {
last_index = static_cast<int32_t>(arr->size()) - 1;
} else if (contents->IsStream()) {
last_index = 0;
}
}
for (int32_t i = 0; i <= last_index; ++i) {
all_dirty_streams.insert(i);
}
}
// --- end embedpdf

// Start regenerating dirty streams.
std::map<int32_t, fxcrt::ostringstream> streams;
std::set<int32_t> empty_streams;
Expand DownExpand Up@@ -510,6 +566,109 @@ void CPDF_PageContentGenerator::UpdateResourcesDict() {
obj_holder_->all_removed_resources_map());
}

ByteString CPDF_PageContentGenerator::RealizeColorSpaceObject(
const CPDF_ColorSpace* cs) {
if (!cs) return ByteString();

const auto fam = cs->GetFamily();
if (fam == CPDF_ColorSpace::Family::kDeviceGray ||
fam == CPDF_ColorSpace::Family::kDeviceRGB ||
fam == CPDF_ColorSpace::Family::kDeviceCMYK) {
return ByteString(); // device spaces don't need a resource
}

if (fam == CPDF_ColorSpace::Family::kICCBased) {
RetainPtr<CPDF_IccProfile> profile = cs->GetIccProfile();
if (!profile) return ByteString();

RetainPtr<const CPDF_StreamAcc> acc = profile->GetStreamAcc();
if (!acc)
return ByteString();
RetainPtr<const CPDF_Stream> icc = acc->GetStream();
if (!icc)
return ByteString();

// Stable cache key based on stream objnum
ByteString key = ByteString::Format("ICCB:%u", icc->GetObjNum());
if (auto hit = obj_holder_->ColorSpaceMapSearch(key))
return *hit;

// IMPORTANT: make array indirect
RetainPtr<CPDF_Array> arr = document_->NewIndirect<CPDF_Array>();
arr->AppendNew<CPDF_Name>("ICCBased");
arr->AppendNew<CPDF_Reference>(document_, icc->GetObjNum());

ByteString name = RealizeResource(arr.Get(), "ColorSpace");
obj_holder_->ColorSpaceMapInsert(key, name);
return name;
}

// (CalGray/CalRGB/Lab/Separation/DeviceN can be added later)
return ByteString();
}

bool CPDF_PageContentGenerator::EmitColor(fxcrt::ostringstream& buf,
const CPDF_Color* color,
bool is_stroke,
CPDF_PageObject* owner) {
if (!color) return false;

if (color->IsColorSpaceGray()) {
auto comps = color->GetRawNonPatternComps();
if (comps.size() == 1) {
WriteFloat(buf, comps[0]) << (is_stroke ? " G " : " g ");
// device space → clear any remembered resource name
if (is_stroke) owner->mutable_color_state().SetStrokeColorSpaceResName({});
else owner->mutable_color_state().SetFillColorSpaceResName({});
return true;
}
return false;
}

if (color->IsColorSpaceRGB()) {
auto rgb = color->GetRGB();
if (!rgb) return false;
WriteFloat(buf, rgb->red) << " ";
WriteFloat(buf, rgb->green) << " ";
WriteFloat(buf, rgb->blue) << (is_stroke ? " RG " : " rg ");
if (is_stroke) owner->mutable_color_state().SetStrokeColorSpaceResName({});
else owner->mutable_color_state().SetFillColorSpaceResName({});
return true;
}

if (color->IsColorSpaceCMYK()) {
auto comps = color->GetRawNonPatternComps(); // expect 4
if (comps.size() == 4) {
WriteFloat(buf, comps[0]) << " ";
WriteFloat(buf, comps[1]) << " ";
WriteFloat(buf, comps[2]) << " ";
WriteFloat(buf, comps[3]) << (is_stroke ? " K " : " k ");
if (is_stroke) owner->mutable_color_state().SetStrokeColorSpaceResName({});
else owner->mutable_color_state().SetFillColorSpaceResName({});
return true;
}
return false;
}

// Non-device: realize resource + scn/SCN
const CPDF_ColorSpace* cs = color->GetColorSpace();
ByteString cs_name = RealizeColorSpaceObject(cs);
if (cs_name.IsEmpty()) return false;

if (is_stroke) owner->mutable_color_state().SetStrokeColorSpaceResName(cs_name);
else owner->mutable_color_state().SetFillColorSpaceResName(cs_name);

buf << "/" << PDF_NameEncode(cs_name) << (is_stroke ? " CS " : " cs ");

auto comps = color->GetRawNonPatternComps();
for (size_t i = 0; i < comps.size(); ++i) {
if (i) buf << " ";
WriteFloat(buf, comps[i]);
}
buf << (is_stroke ? " SCN " : " scn ");
return true;
}

ByteString CPDF_PageContentGenerator::RealizeResource(
const CPDF_Object* pResource,
ByteStringView type) const {
Expand DownExpand Up@@ -819,11 +978,11 @@ void CPDF_PageContentGenerator::ProcessPath(fxcrt::ostringstream* buf,
void CPDF_PageContentGenerator::ProcessGraphics(fxcrt::ostringstream* buf,
CPDF_PageObject* pPageObj) {
*buf << "q ";
if (WriteColorToStream(*buf, pPageObj->color_state().GetFillColor())) {
*buf << " rg ";
if (const CPDF_Color* fill = pPageObj->color_state().GetFillColor()) {
EmitColor(*buf, fill, /*is_stroke=*/false, pPageObj);
}
if (WriteColorToStream(*buf, pPageObj->color_state().GetStrokeColor())) {
*buf << " RG ";
if (const CPDF_Color* stroke = pPageObj->color_state().GetStrokeColor()) {
EmitColor(*buf, stroke, /*is_stroke=*/true, pPageObj);
}
float line_width = pPageObj->graph_state().GetLineWidth();
if (line_width != 1.0f) {
Expand DownExpand Up@@ -909,7 +1068,7 @@ void CPDF_PageContentGenerator::ProcessGraphics(fxcrt::ostringstream* buf,

void CPDF_PageContentGenerator::ProcessDefaultGraphics(
fxcrt::ostringstream* buf) {
*buf << "0 0 0 RG 0 0 0 rg 1 w "
*buf << "1 w "
<< static_cast<int>(CFX_GraphStateData::LineCap::kButt) << " J "
<< static_cast<int>(CFX_GraphStateData::LineJoin::kMiter) << " j\n";
default_graphics_name_ = GetOrCreateDefaultGraphics();
Expand DownExpand Up@@ -948,39 +1107,69 @@ void CPDF_PageContentGenerator::ProcessText(fxcrt::ostringstream* buf,
ProcessGraphics(buf, pTextObj);
*buf << "BT ";

const CFX_Matrix& matrix = pTextObj->GetTextMatrix();
if (!matrix.IsIdentity()) {
WriteMatrix(*buf, matrix) << " Tm ";
// Separate translation (cm) from pure text matrix (Tm)
const CFX_Matrix& M = pTextObj->GetTextMatrix();
if (M.e != 0 || M.f != 0) {
WriteMatrix(*buf, CFX_Matrix(1, 0, 0, 1, M.e, M.f)) << " cm ";
}

CFX_Matrix TmNoTranslate(M.a, M.b, M.c, M.d, 0, 0);
if (!TmNoTranslate.IsIdentity()) {
WriteMatrix(*buf, TmNoTranslate) << " Tm ";
} else {
*buf << "1 0 0 1 0 0 Tm ";
}

// Ensure we have a font.
RetainPtr<CPDF_Font> font(pTextObj->GetFont());
if (!font) {
font = CPDF_Font::GetStockFont(document_, "Helvetica");
}

FontData data;
const CPDF_FontEncoding* pEncoding = nullptr;
if (font->IsType1Font()) {
data.type = "Type1";
pEncoding = font->AsType1Font()->GetEncoding();
} else if (font->IsTrueTypeFont()) {
data.type = "TrueType";
pEncoding = font->AsTrueTypeFont()->GetEncoding();
} else if (font->IsCIDFont()) {
data.type = "Type0";
} else {
return;
// --- Object-number keyed font resource binding ---
// Get the font dictionary; if it's inline, make it indirect so it has a stable objnum.
RetainPtr<const CPDF_Object> pFontDict = font->GetFontDict();
if (pFontDict && pFontDict->IsInline()) {
RetainPtr<CPDF_Object> clone = pFontDict->Clone();
document_->AddIndirectObject(clone);
pFontDict = std::move(clone);
}
data.baseFont = font->GetBaseFontName();

// Some (very old/odd) fonts may not expose a dict; fall back safely.
uint32_t font_objnum = pFontDict ? pFontDict->GetObjNum() : 0;

ByteString dict_name;
std::optional<ByteString> maybe_name = obj_holder_->FontsMapSearch(data);
if (maybe_name.has_value()) {
dict_name = std::move(maybe_name.value());
if (font_objnum) {
if (auto hit = obj_holder_->FontsByObjnumSearch(font_objnum)) {
dict_name = *hit;
} else {
// Realize this exact font object into Resources/Font and cache by objnum.
dict_name = RealizeResource(pFontDict.Get(), "Font");
obj_holder_->FontsByObjnumInsert(font_objnum, dict_name);
}
} else {
RetainPtr<const CPDF_Object> pIndirectFont = font->GetFontDict();
if (pIndirectFont->IsInline()) {
// In this case we assume it must be a standard font
// Last-resort path (should be rare): name by (type, base name) like before.
FontData data;
const CPDF_FontEncoding* pEncoding = nullptr;
if (font->IsType1Font()) {
data.type = "Type1";
pEncoding = font->AsType1Font()->GetEncoding();
} else if (font->IsTrueTypeFont()) {
data.type = "TrueType";
pEncoding = font->AsTrueTypeFont()->GetEncoding();
} else if (font->IsCIDFont()) {
data.type = "Type0";
} else {
*buf << "ET"; // bail out cleanly
EndProcessGraphics(*buf);
return;
}
data.baseFont = font->GetBaseFontName();

if (auto hit = obj_holder_->FontsMapSearch(data)) {
dict_name = *hit;
} else {
// Build a minimal indirect font dict (same as your old code).
auto font_dict = pdfium::MakeRetain<CPDF_Dictionary>();
font_dict->SetNewFor<CPDF_Name>("Type", "Font");
font_dict->SetNewFor<CPDF_Name>("Subtype", data.type);
Expand All@@ -990,22 +1179,34 @@ void CPDF_PageContentGenerator::ProcessText(fxcrt::ostringstream* buf,
pEncoding->Realize(document_->GetByteStringPool()));
}
document_->AddIndirectObject(font_dict);
pIndirectFont = std::move(font_dict);
dict_name = RealizeResource(std::move(font_dict), "Font");
obj_holder_->FontsMapInsert(data, dict_name);
}
dict_name = RealizeResource(std::move(pIndirectFont), "Font");
obj_holder_->FontsMapInsert(data, dict_name);
}

pTextObj->SetResourceName(dict_name);

*buf << "/" << PDF_NameEncode(dict_name) << " ";
WriteFloat(*buf, pTextObj->GetFontSize()) << " Tf ";
*buf << static_cast<int>(pTextObj->GetTextRenderMode()) << " Tr ";
ByteString text;
for (uint32_t charcode : pTextObj->GetCharCodes()) {
if (charcode != CPDF_Font::kInvalidCharCode) {
font->AppendChar(&text, charcode);

const float tc = pTextObj->GetCharSpace();
const float tw = pTextObj->GetWordSpace();

if (tc != 0.0f) WriteFloat(*buf, tc) << " Tc ";
if (tw != 0.0f) WriteFloat(*buf, tw) << " Tw ";

if (TextObjectNeedsTJ(pTextObj)) {
WriteTextAsTJ(*buf, pTextObj, font.Get());
*buf << " ET";
} else {
ByteString text;
for (uint32_t charcode : pTextObj->GetCharCodes()) {
if (charcode != CPDF_Font::kInvalidCharCode)
font->AppendChar(&text, charcode);
}
*buf << PDF_HexEncodeString(text.AsStringView()) << " Tj ET";
}
*buf << PDF_HexEncodeString(text.AsStringView()) << " Tj ET";

EndProcessGraphics(*buf);
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all \u003cpre\u003e\u003ccode\u003e blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks"); } } catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); } })(); (function(){ try { var __m = "github.com"; var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions core/fpdfapi/edit/BUILD.gn
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,6 +21,8 @@ source_set("edit") {
"cpdf_pageorganizer.h",
"cpdf_stringarchivestream.cpp",
"cpdf_stringarchivestream.h",
"cpdf_text_redactor.cpp",
"cpdf_text_redactor.h",
]
configs += [
"../../../:pdfium_strict_config",
Expand Down
295 changes: 248 additions & 47 deletions core/fpdfapi/edit/cpdf_pagecontentgenerator.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -30,6 +30,9 @@
#include "core/fpdfapi/page/cpdf_path.h"
#include "core/fpdfapi/page/cpdf_pathobject.h"
#include "core/fpdfapi/page/cpdf_textobject.h"
#include "core/fpdfapi/page/cpdf_color.h"
#include "core/fpdfapi/page/cpdf_colorspace.h"
#include "core/fpdfapi/page/cpdf_iccprofile.h"
#include "core/fpdfapi/parser/cpdf_array.h"
#include "core/fpdfapi/parser/cpdf_dictionary.h"
#include "core/fpdfapi/parser/cpdf_document.h"
Expand All@@ -53,27 +56,56 @@ namespace {
// - ColorSpace
// - Pattern
// - Shading
constexpr const char* kResourceKeys[] = {"ExtGState", "Font", "XObject"};
constexpr const char* kResourceKeys[] = {"ExtGState", "Font", "XObject", "ColorSpace"};

// Key: The resource type.
// Value: The resource names of a given type.
using ResourcesMap = std::map<ByteString, std::set<ByteString>>;

// Returns whether it wrote to `buf` or not.
bool WriteColorToStream(fxcrt::ostringstream& buf, const CPDF_Color* color) {
if (!color || (!color->IsColorSpaceRGB() && !color->IsColorSpaceGray())) {
return false;
bool TextObjectNeedsTJ(const CPDF_TextObject* obj) {
// We don’t have a public accessor for char_codes_, but we can reuse CountItems()
// and GetItemInfo(i). GetItemInfo() gives us char_code_ and (for vert writing)
// origin_. We only need to see if any item has the sentinel.
for (size_t i = 0, n = obj->CountItems(); i < n; ++i) {
auto it = obj->GetItemInfo(i);
if (it.char_code_ == CPDF_Font::kInvalidCharCode)
return true;
}
return false;
}

std::optional<FX_RGB_STRUCT<float>> colors = color->GetRGB();
if (!colors.has_value()) {
return false;
void WriteTextAsTJ(fxcrt::ostringstream& buf,
CPDF_TextObject* obj,
CPDF_Font* font) {
buf << "[ ";
ByteString hexChunk;

for (size_t i = 0, n = obj->CountItems(); i < n; ++i) {
CPDF_TextObject::Item it = obj->GetItemInfo(i);

if (it.char_code_ == CPDF_Font::kInvalidCharCode) {
if (!hexChunk.IsEmpty()) {
buf << PDF_HexEncodeString(hexChunk.AsStringView()) << " ";
hexChunk.clear();
}
float thousandths = 0.0f;
if (obj->GetSeparatorAdjustment(i, &thousandths)) {
// TJ numbers are interpreted as “subtract this from the text position”,
// which matches how CalcPositionDataInternal() used the stored value:
// curpos -= (thousandths * fontSize)/1000. So we emit the value as-is.
WriteFloat(buf, thousandths);
buf << " ";
}
continue;
}

font->AppendChar(&hexChunk, it.char_code_);
}

WriteFloat(buf, colors.value().red) << " ";
WriteFloat(buf, colors.value().green) << " ";
WriteFloat(buf, colors.value().blue);
return true;
if (!hexChunk.IsEmpty()) {
buf << PDF_HexEncodeString(hexChunk.AsStringView()) << " ";
}
buf << "] TJ";
}

// Balances the "q" operator ProcessGraphics() emitted.
Expand DownExpand Up@@ -103,6 +135,11 @@ void RecordPageObjectResourceUsage(const CPDF_PageObject* page_object,
CHECK(!name.IsEmpty());
seen_resources["ExtGState"].insert(name);
}
const CPDF_ColorState& cs = page_object->color_state();
if (!cs.GetFillColorSpaceResName().IsEmpty())
seen_resources["ColorSpace"].insert(cs.GetFillColorSpaceResName());
if (!cs.GetStrokeColorSpaceResName().IsEmpty())
seen_resources["ColorSpace"].insert(cs.GetStrokeColorSpaceResName());
}

CPDF_PageObjectHolder::RemovedResourceMap RemoveUnusedResources(
Expand DownExpand Up@@ -357,6 +394,25 @@ CPDF_PageContentGenerator::GenerateModifiedStreams() {
all_dirty_streams.insert(marked_dirty_streams.begin(),
marked_dirty_streams.end());

// --- embedpdf: if anything is dirty, regenerate *all* page content streams.
// Rationale: CTM / graphics-state handoff between streams means rewriting
// only a subset can leave the concatenated effect inconsistent.
if (!all_dirty_streams.empty()) {
int32_t last_index = -1;
if (RetainPtr<const CPDF_Object> contents =
obj_holder_->GetDict()->GetObjectFor(pdfium::page_object::kContents)) {
if (const CPDF_Array* arr = contents->AsArray()) {
last_index = static_cast<int32_t>(arr->size()) - 1;
} else if (contents->IsStream()) {
last_index = 0;
}
}
for (int32_t i = 0; i <= last_index; ++i) {
all_dirty_streams.insert(i);
}
}
// --- end embedpdf

// Start regenerating dirty streams.
std::map<int32_t, fxcrt::ostringstream> streams;
std::set<int32_t> empty_streams;
Expand DownExpand Up@@ -510,6 +566,109 @@ void CPDF_PageContentGenerator::UpdateResourcesDict() {
obj_holder_->all_removed_resources_map());
}

ByteString CPDF_PageContentGenerator::RealizeColorSpaceObject(
const CPDF_ColorSpace* cs) {
if (!cs) return ByteString();

const auto fam = cs->GetFamily();
if (fam == CPDF_ColorSpace::Family::kDeviceGray ||
fam == CPDF_ColorSpace::Family::kDeviceRGB ||
fam == CPDF_ColorSpace::Family::kDeviceCMYK) {
return ByteString(); // device spaces don't need a resource
}

if (fam == CPDF_ColorSpace::Family::kICCBased) {
RetainPtr<CPDF_IccProfile> profile = cs->GetIccProfile();
if (!profile) return ByteString();

RetainPtr<const CPDF_StreamAcc> acc = profile->GetStreamAcc();
if (!acc)
return ByteString();
RetainPtr<const CPDF_Stream> icc = acc->GetStream();
if (!icc)
return ByteString();

// Stable cache key based on stream objnum
ByteString key = ByteString::Format("ICCB:%u", icc->GetObjNum());
if (auto hit = obj_holder_->ColorSpaceMapSearch(key))
return *hit;

// IMPORTANT: make array indirect
RetainPtr<CPDF_Array> arr = document_->NewIndirect<CPDF_Array>();
arr->AppendNew<CPDF_Name>("ICCBased");
arr->AppendNew<CPDF_Reference>(document_, icc->GetObjNum());

ByteString name = RealizeResource(arr.Get(), "ColorSpace");
obj_holder_->ColorSpaceMapInsert(key, name);
return name;
}

// (CalGray/CalRGB/Lab/Separation/DeviceN can be added later)
return ByteString();
}

bool CPDF_PageContentGenerator::EmitColor(fxcrt::ostringstream& buf,
const CPDF_Color* color,
bool is_stroke,
CPDF_PageObject* owner) {
if (!color) return false;

if (color->IsColorSpaceGray()) {
auto comps = color->GetRawNonPatternComps();
if (comps.size() == 1) {
WriteFloat(buf, comps[0]) << (is_stroke ? " G " : " g ");
// device space → clear any remembered resource name
if (is_stroke) owner->mutable_color_state().SetStrokeColorSpaceResName({});
else owner->mutable_color_state().SetFillColorSpaceResName({});
return true;
}
return false;
}

if (color->IsColorSpaceRGB()) {
auto rgb = color->GetRGB();
if (!rgb) return false;
WriteFloat(buf, rgb->red) << " ";
WriteFloat(buf, rgb->green) << " ";
WriteFloat(buf, rgb->blue) << (is_stroke ? " RG " : " rg ");
if (is_stroke) owner->mutable_color_state().SetStrokeColorSpaceResName({});
else owner->mutable_color_state().SetFillColorSpaceResName({});
return true;
}

if (color->IsColorSpaceCMYK()) {
auto comps = color->GetRawNonPatternComps(); // expect 4
if (comps.size() == 4) {
WriteFloat(buf, comps[0]) << " ";
WriteFloat(buf, comps[1]) << " ";
WriteFloat(buf, comps[2]) << " ";
WriteFloat(buf, comps[3]) << (is_stroke ? " K " : " k ");
if (is_stroke) owner->mutable_color_state().SetStrokeColorSpaceResName({});
else owner->mutable_color_state().SetFillColorSpaceResName({});
return true;
}
return false;
}

// Non-device: realize resource + scn/SCN
const CPDF_ColorSpace* cs = color->GetColorSpace();
ByteString cs_name = RealizeColorSpaceObject(cs);
if (cs_name.IsEmpty()) return false;

if (is_stroke) owner->mutable_color_state().SetStrokeColorSpaceResName(cs_name);
else owner->mutable_color_state().SetFillColorSpaceResName(cs_name);

buf << "/" << PDF_NameEncode(cs_name) << (is_stroke ? " CS " : " cs ");

auto comps = color->GetRawNonPatternComps();
for (size_t i = 0; i < comps.size(); ++i) {
if (i) buf << " ";
WriteFloat(buf, comps[i]);
}
buf << (is_stroke ? " SCN " : " scn ");
return true;
}

ByteString CPDF_PageContentGenerator::RealizeResource(
const CPDF_Object* pResource,
ByteStringView type) const {
Expand DownExpand Up@@ -819,11 +978,11 @@ void CPDF_PageContentGenerator::ProcessPath(fxcrt::ostringstream* buf,
void CPDF_PageContentGenerator::ProcessGraphics(fxcrt::ostringstream* buf,
CPDF_PageObject* pPageObj) {
*buf << "q ";
if (WriteColorToStream(*buf, pPageObj->color_state().GetFillColor())) {
*buf << " rg ";
if (const CPDF_Color* fill = pPageObj->color_state().GetFillColor()) {
EmitColor(*buf, fill, /*is_stroke=*/false, pPageObj);
}
if (WriteColorToStream(*buf, pPageObj->color_state().GetStrokeColor())) {
*buf << " RG ";
if (const CPDF_Color* stroke = pPageObj->color_state().GetStrokeColor()) {
EmitColor(*buf, stroke, /*is_stroke=*/true, pPageObj);
}
float line_width = pPageObj->graph_state().GetLineWidth();
if (line_width != 1.0f) {
Expand DownExpand Up@@ -909,7 +1068,7 @@ void CPDF_PageContentGenerator::ProcessGraphics(fxcrt::ostringstream* buf,

void CPDF_PageContentGenerator::ProcessDefaultGraphics(
fxcrt::ostringstream* buf) {
*buf << "0 0 0 RG 0 0 0 rg 1 w "
*buf << "1 w "
<< static_cast<int>(CFX_GraphStateData::LineCap::kButt) << " J "
<< static_cast<int>(CFX_GraphStateData::LineJoin::kMiter) << " j\n";
default_graphics_name_ = GetOrCreateDefaultGraphics();
Expand DownExpand Up@@ -948,39 +1107,69 @@ void CPDF_PageContentGenerator::ProcessText(fxcrt::ostringstream* buf,
ProcessGraphics(buf, pTextObj);
*buf << "BT ";

const CFX_Matrix& matrix = pTextObj->GetTextMatrix();
if (!matrix.IsIdentity()) {
WriteMatrix(*buf, matrix) << " Tm ";
// Separate translation (cm) from pure text matrix (Tm)
const CFX_Matrix& M = pTextObj->GetTextMatrix();
if (M.e != 0 || M.f != 0) {
WriteMatrix(*buf, CFX_Matrix(1, 0, 0, 1, M.e, M.f)) << " cm ";
}

CFX_Matrix TmNoTranslate(M.a, M.b, M.c, M.d, 0, 0);
if (!TmNoTranslate.IsIdentity()) {
WriteMatrix(*buf, TmNoTranslate) << " Tm ";
} else {
*buf << "1 0 0 1 0 0 Tm ";
}

// Ensure we have a font.
RetainPtr<CPDF_Font> font(pTextObj->GetFont());
if (!font) {
font = CPDF_Font::GetStockFont(document_, "Helvetica");
}

FontData data;
const CPDF_FontEncoding* pEncoding = nullptr;
if (font->IsType1Font()) {
data.type = "Type1";
pEncoding = font->AsType1Font()->GetEncoding();
} else if (font->IsTrueTypeFont()) {
data.type = "TrueType";
pEncoding = font->AsTrueTypeFont()->GetEncoding();
} else if (font->IsCIDFont()) {
data.type = "Type0";
} else {
return;
// --- Object-number keyed font resource binding ---
// Get the font dictionary; if it's inline, make it indirect so it has a stable objnum.
RetainPtr<const CPDF_Object> pFontDict = font->GetFontDict();
if (pFontDict && pFontDict->IsInline()) {
RetainPtr<CPDF_Object> clone = pFontDict->Clone();
document_->AddIndirectObject(clone);
pFontDict = std::move(clone);
}
data.baseFont = font->GetBaseFontName();

// Some (very old/odd) fonts may not expose a dict; fall back safely.
uint32_t font_objnum = pFontDict ? pFontDict->GetObjNum() : 0;

ByteString dict_name;
std::optional<ByteString> maybe_name = obj_holder_->FontsMapSearch(data);
if (maybe_name.has_value()) {
dict_name = std::move(maybe_name.value());
if (font_objnum) {
if (auto hit = obj_holder_->FontsByObjnumSearch(font_objnum)) {
dict_name = *hit;
} else {
// Realize this exact font object into Resources/Font and cache by objnum.
dict_name = RealizeResource(pFontDict.Get(), "Font");
obj_holder_->FontsByObjnumInsert(font_objnum, dict_name);
}
} else {
RetainPtr<const CPDF_Object> pIndirectFont = font->GetFontDict();
if (pIndirectFont->IsInline()) {
// In this case we assume it must be a standard font
// Last-resort path (should be rare): name by (type, base name) like before.
FontData data;
const CPDF_FontEncoding* pEncoding = nullptr;
if (font->IsType1Font()) {
data.type = "Type1";
pEncoding = font->AsType1Font()->GetEncoding();
} else if (font->IsTrueTypeFont()) {
data.type = "TrueType";
pEncoding = font->AsTrueTypeFont()->GetEncoding();
} else if (font->IsCIDFont()) {
data.type = "Type0";
} else {
*buf << "ET"; // bail out cleanly
EndProcessGraphics(*buf);
return;
}
data.baseFont = font->GetBaseFontName();

if (auto hit = obj_holder_->FontsMapSearch(data)) {
dict_name = *hit;
} else {
// Build a minimal indirect font dict (same as your old code).
auto font_dict = pdfium::MakeRetain<CPDF_Dictionary>();
font_dict->SetNewFor<CPDF_Name>("Type", "Font");
font_dict->SetNewFor<CPDF_Name>("Subtype", data.type);
Expand All@@ -990,22 +1179,34 @@ void CPDF_PageContentGenerator::ProcessText(fxcrt::ostringstream* buf,
pEncoding->Realize(document_->GetByteStringPool()));
}
document_->AddIndirectObject(font_dict);
pIndirectFont = std::move(font_dict);
dict_name = RealizeResource(std::move(font_dict), "Font");
obj_holder_->FontsMapInsert(data, dict_name);
}
dict_name = RealizeResource(std::move(pIndirectFont), "Font");
obj_holder_->FontsMapInsert(data, dict_name);
}

pTextObj->SetResourceName(dict_name);

*buf << "/" << PDF_NameEncode(dict_name) << " ";
WriteFloat(*buf, pTextObj->GetFontSize()) << " Tf ";
*buf << static_cast<int>(pTextObj->GetTextRenderMode()) << " Tr ";
ByteString text;
for (uint32_t charcode : pTextObj->GetCharCodes()) {
if (charcode != CPDF_Font::kInvalidCharCode) {
font->AppendChar(&text, charcode);

const float tc = pTextObj->GetCharSpace();
const float tw = pTextObj->GetWordSpace();

if (tc != 0.0f) WriteFloat(*buf, tc) << " Tc ";
if (tw != 0.0f) WriteFloat(*buf, tw) << " Tw ";

if (TextObjectNeedsTJ(pTextObj)) {
WriteTextAsTJ(*buf, pTextObj, font.Get());
*buf << " ET";
} else {
ByteString text;
for (uint32_t charcode : pTextObj->GetCharCodes()) {
if (charcode != CPDF_Font::kInvalidCharCode)
font->AppendChar(&text, charcode);
}
*buf << PDF_HexEncodeString(text.AsStringView()) << " Tj ET";
}
*buf << PDF_HexEncodeString(text.AsStringView()) << " Tj ET";

EndProcessGraphics(*buf);
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions core/fpdfapi/edit/BUILD.gn
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,6 +21,8 @@ source_set("edit") {
"cpdf_pageorganizer.h",
"cpdf_stringarchivestream.cpp",
"cpdf_stringarchivestream.h",
"cpdf_text_redactor.cpp",
"cpdf_text_redactor.h",
]
configs += [
"../../../:pdfium_strict_config",
Expand Down
295 changes: 248 additions & 47 deletions core/fpdfapi/edit/cpdf_pagecontentgenerator.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -30,6 +30,9 @@
#include "core/fpdfapi/page/cpdf_path.h"
#include "core/fpdfapi/page/cpdf_pathobject.h"
#include "core/fpdfapi/page/cpdf_textobject.h"
#include "core/fpdfapi/page/cpdf_color.h"
#include "core/fpdfapi/page/cpdf_colorspace.h"
#include "core/fpdfapi/page/cpdf_iccprofile.h"
#include "core/fpdfapi/parser/cpdf_array.h"
#include "core/fpdfapi/parser/cpdf_dictionary.h"
#include "core/fpdfapi/parser/cpdf_document.h"
Expand All@@ -53,27 +56,56 @@ namespace {
// - ColorSpace
// - Pattern
// - Shading
constexpr const char* kResourceKeys[] = {"ExtGState", "Font", "XObject"};
constexpr const char* kResourceKeys[] = {"ExtGState", "Font", "XObject", "ColorSpace"};

// Key: The resource type.
// Value: The resource names of a given type.
using ResourcesMap = std::map<ByteString, std::set<ByteString>>;

// Returns whether it wrote to `buf` or not.
bool WriteColorToStream(fxcrt::ostringstream& buf, const CPDF_Color* color) {
if (!color || (!color->IsColorSpaceRGB() && !color->IsColorSpaceGray())) {
return false;
bool TextObjectNeedsTJ(const CPDF_TextObject* obj) {
// We don’t have a public accessor for char_codes_, but we can reuse CountItems()
// and GetItemInfo(i). GetItemInfo() gives us char_code_ and (for vert writing)
// origin_. We only need to see if any item has the sentinel.
for (size_t i = 0, n = obj->CountItems(); i < n; ++i) {
auto it = obj->GetItemInfo(i);
if (it.char_code_ == CPDF_Font::kInvalidCharCode)
return true;
}
return false;
}

std::optional<FX_RGB_STRUCT<float>> colors = color->GetRGB();
if (!colors.has_value()) {
return false;
void WriteTextAsTJ(fxcrt::ostringstream& buf,
CPDF_TextObject* obj,
CPDF_Font* font) {
buf << "[ ";
ByteString hexChunk;

for (size_t i = 0, n = obj->CountItems(); i < n; ++i) {
CPDF_TextObject::Item it = obj->GetItemInfo(i);

if (it.char_code_ == CPDF_Font::kInvalidCharCode) {
if (!hexChunk.IsEmpty()) {
buf << PDF_HexEncodeString(hexChunk.AsStringView()) << " ";
hexChunk.clear();
}
float thousandths = 0.0f;
if (obj->GetSeparatorAdjustment(i, &thousandths)) {
// TJ numbers are interpreted as “subtract this from the text position”,
// which matches how CalcPositionDataInternal() used the stored value:
// curpos -= (thousandths * fontSize)/1000. So we emit the value as-is.
WriteFloat(buf, thousandths);
buf << " ";
}
continue;
}

font->AppendChar(&hexChunk, it.char_code_);
}

WriteFloat(buf, colors.value().red) << " ";
WriteFloat(buf, colors.value().green) << " ";
WriteFloat(buf, colors.value().blue);
return true;
if (!hexChunk.IsEmpty()) {
buf << PDF_HexEncodeString(hexChunk.AsStringView()) << " ";
}
buf << "] TJ";
}

// Balances the "q" operator ProcessGraphics() emitted.
Expand DownExpand Up@@ -103,6 +135,11 @@ void RecordPageObjectResourceUsage(const CPDF_PageObject* page_object,
CHECK(!name.IsEmpty());
seen_resources["ExtGState"].insert(name);
}
const CPDF_ColorState& cs = page_object->color_state();
if (!cs.GetFillColorSpaceResName().IsEmpty())
seen_resources["ColorSpace"].insert(cs.GetFillColorSpaceResName());
if (!cs.GetStrokeColorSpaceResName().IsEmpty())
seen_resources["ColorSpace"].insert(cs.GetStrokeColorSpaceResName());
}

CPDF_PageObjectHolder::RemovedResourceMap RemoveUnusedResources(
Expand DownExpand Up@@ -357,6 +394,25 @@ CPDF_PageContentGenerator::GenerateModifiedStreams() {
all_dirty_streams.insert(marked_dirty_streams.begin(),
marked_dirty_streams.end());

// --- embedpdf: if anything is dirty, regenerate *all* page content streams.
// Rationale: CTM / graphics-state handoff between streams means rewriting
// only a subset can leave the concatenated effect inconsistent.
if (!all_dirty_streams.empty()) {
int32_t last_index = -1;
if (RetainPtr<const CPDF_Object> contents =
obj_holder_->GetDict()->GetObjectFor(pdfium::page_object::kContents)) {
if (const CPDF_Array* arr = contents->AsArray()) {
last_index = static_cast<int32_t>(arr->size()) - 1;
} else if (contents->IsStream()) {
last_index = 0;
}
}
for (int32_t i = 0; i <= last_index; ++i) {
all_dirty_streams.insert(i);
}
}
// --- end embedpdf

// Start regenerating dirty streams.
std::map<int32_t, fxcrt::ostringstream> streams;
std::set<int32_t> empty_streams;
Expand DownExpand Up@@ -510,6 +566,109 @@ void CPDF_PageContentGenerator::UpdateResourcesDict() {
obj_holder_->all_removed_resources_map());
}

ByteString CPDF_PageContentGenerator::RealizeColorSpaceObject(
const CPDF_ColorSpace* cs) {
if (!cs) return ByteString();

const auto fam = cs->GetFamily();
if (fam == CPDF_ColorSpace::Family::kDeviceGray ||
fam == CPDF_ColorSpace::Family::kDeviceRGB ||
fam == CPDF_ColorSpace::Family::kDeviceCMYK) {
return ByteString(); // device spaces don't need a resource
}

if (fam == CPDF_ColorSpace::Family::kICCBased) {
RetainPtr<CPDF_IccProfile> profile = cs->GetIccProfile();
if (!profile) return ByteString();

RetainPtr<const CPDF_StreamAcc> acc = profile->GetStreamAcc();
if (!acc)
return ByteString();
RetainPtr<const CPDF_Stream> icc = acc->GetStream();
if (!icc)
return ByteString();

// Stable cache key based on stream objnum
ByteString key = ByteString::Format("ICCB:%u", icc->GetObjNum());
if (auto hit = obj_holder_->ColorSpaceMapSearch(key))
return *hit;

// IMPORTANT: make array indirect
RetainPtr<CPDF_Array> arr = document_->NewIndirect<CPDF_Array>();
arr->AppendNew<CPDF_Name>("ICCBased");
arr->AppendNew<CPDF_Reference>(document_, icc->GetObjNum());

ByteString name = RealizeResource(arr.Get(), "ColorSpace");
obj_holder_->ColorSpaceMapInsert(key, name);
return name;
}

// (CalGray/CalRGB/Lab/Separation/DeviceN can be added later)
return ByteString();
}

bool CPDF_PageContentGenerator::EmitColor(fxcrt::ostringstream& buf,
const CPDF_Color* color,
bool is_stroke,
CPDF_PageObject* owner) {
if (!color) return false;

if (color->IsColorSpaceGray()) {
auto comps = color->GetRawNonPatternComps();
if (comps.size() == 1) {
WriteFloat(buf, comps[0]) << (is_stroke ? " G " : " g ");
// device space → clear any remembered resource name
if (is_stroke) owner->mutable_color_state().SetStrokeColorSpaceResName({});
else owner->mutable_color_state().SetFillColorSpaceResName({});
return true;
}
return false;
}

if (color->IsColorSpaceRGB()) {
auto rgb = color->GetRGB();
if (!rgb) return false;
WriteFloat(buf, rgb->red) << " ";
WriteFloat(buf, rgb->green) << " ";
WriteFloat(buf, rgb->blue) << (is_stroke ? " RG " : " rg ");
if (is_stroke) owner->mutable_color_state().SetStrokeColorSpaceResName({});
else owner->mutable_color_state().SetFillColorSpaceResName({});
return true;
}

if (color->IsColorSpaceCMYK()) {
auto comps = color->GetRawNonPatternComps(); // expect 4
if (comps.size() == 4) {
WriteFloat(buf, comps[0]) << " ";
WriteFloat(buf, comps[1]) << " ";
WriteFloat(buf, comps[2]) << " ";
WriteFloat(buf, comps[3]) << (is_stroke ? " K " : " k ");
if (is_stroke) owner->mutable_color_state().SetStrokeColorSpaceResName({});
else owner->mutable_color_state().SetFillColorSpaceResName({});
return true;
}
return false;
}

// Non-device: realize resource + scn/SCN
const CPDF_ColorSpace* cs = color->GetColorSpace();
ByteString cs_name = RealizeColorSpaceObject(cs);
if (cs_name.IsEmpty()) return false;

if (is_stroke) owner->mutable_color_state().SetStrokeColorSpaceResName(cs_name);
else owner->mutable_color_state().SetFillColorSpaceResName(cs_name);

buf << "/" << PDF_NameEncode(cs_name) << (is_stroke ? " CS " : " cs ");

auto comps = color->GetRawNonPatternComps();
for (size_t i = 0; i < comps.size(); ++i) {
if (i) buf << " ";
WriteFloat(buf, comps[i]);
}
buf << (is_stroke ? " SCN " : " scn ");
return true;
}

ByteString CPDF_PageContentGenerator::RealizeResource(
const CPDF_Object* pResource,
ByteStringView type) const {
Expand DownExpand Up@@ -819,11 +978,11 @@ void CPDF_PageContentGenerator::ProcessPath(fxcrt::ostringstream* buf,
void CPDF_PageContentGenerator::ProcessGraphics(fxcrt::ostringstream* buf,
CPDF_PageObject* pPageObj) {
*buf << "q ";
if (WriteColorToStream(*buf, pPageObj->color_state().GetFillColor())) {
*buf << " rg ";
if (const CPDF_Color* fill = pPageObj->color_state().GetFillColor()) {
EmitColor(*buf, fill, /*is_stroke=*/false, pPageObj);
}
if (WriteColorToStream(*buf, pPageObj->color_state().GetStrokeColor())) {
*buf << " RG ";
if (const CPDF_Color* stroke = pPageObj->color_state().GetStrokeColor()) {
EmitColor(*buf, stroke, /*is_stroke=*/true, pPageObj);
}
float line_width = pPageObj->graph_state().GetLineWidth();
if (line_width != 1.0f) {
Expand DownExpand Up@@ -909,7 +1068,7 @@ void CPDF_PageContentGenerator::ProcessGraphics(fxcrt::ostringstream* buf,

void CPDF_PageContentGenerator::ProcessDefaultGraphics(
fxcrt::ostringstream* buf) {
*buf << "0 0 0 RG 0 0 0 rg 1 w "
*buf << "1 w "
<< static_cast<int>(CFX_GraphStateData::LineCap::kButt) << " J "
<< static_cast<int>(CFX_GraphStateData::LineJoin::kMiter) << " j\n";
default_graphics_name_ = GetOrCreateDefaultGraphics();
Expand DownExpand Up@@ -948,39 +1107,69 @@ void CPDF_PageContentGenerator::ProcessText(fxcrt::ostringstream* buf,
ProcessGraphics(buf, pTextObj);
*buf << "BT ";

const CFX_Matrix& matrix = pTextObj->GetTextMatrix();
if (!matrix.IsIdentity()) {
WriteMatrix(*buf, matrix) << " Tm ";
// Separate translation (cm) from pure text matrix (Tm)
const CFX_Matrix& M = pTextObj->GetTextMatrix();
if (M.e != 0 || M.f != 0) {
WriteMatrix(*buf, CFX_Matrix(1, 0, 0, 1, M.e, M.f)) << " cm ";
}

CFX_Matrix TmNoTranslate(M.a, M.b, M.c, M.d, 0, 0);
if (!TmNoTranslate.IsIdentity()) {
WriteMatrix(*buf, TmNoTranslate) << " Tm ";
} else {
*buf << "1 0 0 1 0 0 Tm ";
}

// Ensure we have a font.
RetainPtr<CPDF_Font> font(pTextObj->GetFont());
if (!font) {
font = CPDF_Font::GetStockFont(document_, "Helvetica");
}

FontData data;
const CPDF_FontEncoding* pEncoding = nullptr;
if (font->IsType1Font()) {
data.type = "Type1";
pEncoding = font->AsType1Font()->GetEncoding();
} else if (font->IsTrueTypeFont()) {
data.type = "TrueType";
pEncoding = font->AsTrueTypeFont()->GetEncoding();
} else if (font->IsCIDFont()) {
data.type = "Type0";
} else {
return;
// --- Object-number keyed font resource binding ---
// Get the font dictionary; if it's inline, make it indirect so it has a stable objnum.
RetainPtr<const CPDF_Object> pFontDict = font->GetFontDict();
if (pFontDict && pFontDict->IsInline()) {
RetainPtr<CPDF_Object> clone = pFontDict->Clone();
document_->AddIndirectObject(clone);
pFontDict = std::move(clone);
}
data.baseFont = font->GetBaseFontName();

// Some (very old/odd) fonts may not expose a dict; fall back safely.
uint32_t font_objnum = pFontDict ? pFontDict->GetObjNum() : 0;

ByteString dict_name;
std::optional<ByteString> maybe_name = obj_holder_->FontsMapSearch(data);
if (maybe_name.has_value()) {
dict_name = std::move(maybe_name.value());
if (font_objnum) {
if (auto hit = obj_holder_->FontsByObjnumSearch(font_objnum)) {
dict_name = *hit;
} else {
// Realize this exact font object into Resources/Font and cache by objnum.
dict_name = RealizeResource(pFontDict.Get(), "Font");
obj_holder_->FontsByObjnumInsert(font_objnum, dict_name);
}
} else {
RetainPtr<const CPDF_Object> pIndirectFont = font->GetFontDict();
if (pIndirectFont->IsInline()) {
// In this case we assume it must be a standard font
// Last-resort path (should be rare): name by (type, base name) like before.
FontData data;
const CPDF_FontEncoding* pEncoding = nullptr;
if (font->IsType1Font()) {
data.type = "Type1";
pEncoding = font->AsType1Font()->GetEncoding();
} else if (font->IsTrueTypeFont()) {
data.type = "TrueType";
pEncoding = font->AsTrueTypeFont()->GetEncoding();
} else if (font->IsCIDFont()) {
data.type = "Type0";
} else {
*buf << "ET"; // bail out cleanly
EndProcessGraphics(*buf);
return;
}
data.baseFont = font->GetBaseFontName();

if (auto hit = obj_holder_->FontsMapSearch(data)) {
dict_name = *hit;
} else {
// Build a minimal indirect font dict (same as your old code).
auto font_dict = pdfium::MakeRetain<CPDF_Dictionary>();
font_dict->SetNewFor<CPDF_Name>("Type", "Font");
font_dict->SetNewFor<CPDF_Name>("Subtype", data.type);
Expand All@@ -990,22 +1179,34 @@ void CPDF_PageContentGenerator::ProcessText(fxcrt::ostringstream* buf,
pEncoding->Realize(document_->GetByteStringPool()));
}
document_->AddIndirectObject(font_dict);
pIndirectFont = std::move(font_dict);
dict_name = RealizeResource(std::move(font_dict), "Font");
obj_holder_->FontsMapInsert(data, dict_name);
}
dict_name = RealizeResource(std::move(pIndirectFont), "Font");
obj_holder_->FontsMapInsert(data, dict_name);
}

pTextObj->SetResourceName(dict_name);

*buf << "/" << PDF_NameEncode(dict_name) << " ";
WriteFloat(*buf, pTextObj->GetFontSize()) << " Tf ";
*buf << static_cast<int>(pTextObj->GetTextRenderMode()) << " Tr ";
ByteString text;
for (uint32_t charcode : pTextObj->GetCharCodes()) {
if (charcode != CPDF_Font::kInvalidCharCode) {
font->AppendChar(&text, charcode);

const float tc = pTextObj->GetCharSpace();
const float tw = pTextObj->GetWordSpace();

if (tc != 0.0f) WriteFloat(*buf, tc) << " Tc ";
if (tw != 0.0f) WriteFloat(*buf, tw) << " Tw ";

if (TextObjectNeedsTJ(pTextObj)) {
WriteTextAsTJ(*buf, pTextObj, font.Get());
*buf << " ET";
} else {
ByteString text;
for (uint32_t charcode : pTextObj->GetCharCodes()) {
if (charcode != CPDF_Font::kInvalidCharCode)
font->AppendChar(&text, charcode);
}
*buf << PDF_HexEncodeString(text.AsStringView()) << " Tj ET";
}
*buf << PDF_HexEncodeString(text.AsStringView()) << " Tj ET";

EndProcessGraphics(*buf);
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length \u003e 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions core/fpdfapi/edit/BUILD.gn
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,6 +21,8 @@ source_set("edit") {
"cpdf_pageorganizer.h",
"cpdf_stringarchivestream.cpp",
"cpdf_stringarchivestream.h",
"cpdf_text_redactor.cpp",
"cpdf_text_redactor.h",
]
configs += [
"../../../:pdfium_strict_config",
Expand Down
295 changes: 248 additions & 47 deletions core/fpdfapi/edit/cpdf_pagecontentgenerator.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -30,6 +30,9 @@
#include "core/fpdfapi/page/cpdf_path.h"
#include "core/fpdfapi/page/cpdf_pathobject.h"
#include "core/fpdfapi/page/cpdf_textobject.h"
#include "core/fpdfapi/page/cpdf_color.h"
#include "core/fpdfapi/page/cpdf_colorspace.h"
#include "core/fpdfapi/page/cpdf_iccprofile.h"
#include "core/fpdfapi/parser/cpdf_array.h"
#include "core/fpdfapi/parser/cpdf_dictionary.h"
#include "core/fpdfapi/parser/cpdf_document.h"
Expand All@@ -53,27 +56,56 @@ namespace {
// - ColorSpace
// - Pattern
// - Shading
constexpr const char* kResourceKeys[] = {"ExtGState", "Font", "XObject"};
constexpr const char* kResourceKeys[] = {"ExtGState", "Font", "XObject", "ColorSpace"};

// Key: The resource type.
// Value: The resource names of a given type.
using ResourcesMap = std::map<ByteString, std::set<ByteString>>;

// Returns whether it wrote to `buf` or not.
bool WriteColorToStream(fxcrt::ostringstream& buf, const CPDF_Color* color) {
if (!color || (!color->IsColorSpaceRGB() && !color->IsColorSpaceGray())) {
return false;
bool TextObjectNeedsTJ(const CPDF_TextObject* obj) {
// We don’t have a public accessor for char_codes_, but we can reuse CountItems()
// and GetItemInfo(i). GetItemInfo() gives us char_code_ and (for vert writing)
// origin_. We only need to see if any item has the sentinel.
for (size_t i = 0, n = obj->CountItems(); i < n; ++i) {
auto it = obj->GetItemInfo(i);
if (it.char_code_ == CPDF_Font::kInvalidCharCode)
return true;
}
return false;
}

std::optional<FX_RGB_STRUCT<float>> colors = color->GetRGB();
if (!colors.has_value()) {
return false;
void WriteTextAsTJ(fxcrt::ostringstream& buf,
CPDF_TextObject* obj,
CPDF_Font* font) {
buf << "[ ";
ByteString hexChunk;

for (size_t i = 0, n = obj->CountItems(); i < n; ++i) {
CPDF_TextObject::Item it = obj->GetItemInfo(i);

if (it.char_code_ == CPDF_Font::kInvalidCharCode) {
if (!hexChunk.IsEmpty()) {
buf << PDF_HexEncodeString(hexChunk.AsStringView()) << " ";
hexChunk.clear();
}
float thousandths = 0.0f;
if (obj->GetSeparatorAdjustment(i, &thousandths)) {
// TJ numbers are interpreted as “subtract this from the text position”,
// which matches how CalcPositionDataInternal() used the stored value:
// curpos -= (thousandths * fontSize)/1000. So we emit the value as-is.
WriteFloat(buf, thousandths);
buf << " ";
}
continue;
}

font->AppendChar(&hexChunk, it.char_code_);
}

WriteFloat(buf, colors.value().red) << " ";
WriteFloat(buf, colors.value().green) << " ";
WriteFloat(buf, colors.value().blue);
return true;
if (!hexChunk.IsEmpty()) {
buf << PDF_HexEncodeString(hexChunk.AsStringView()) << " ";
}
buf << "] TJ";
}

// Balances the "q" operator ProcessGraphics() emitted.
Expand DownExpand Up@@ -103,6 +135,11 @@ void RecordPageObjectResourceUsage(const CPDF_PageObject* page_object,
CHECK(!name.IsEmpty());
seen_resources["ExtGState"].insert(name);
}
const CPDF_ColorState& cs = page_object->color_state();
if (!cs.GetFillColorSpaceResName().IsEmpty())
seen_resources["ColorSpace"].insert(cs.GetFillColorSpaceResName());
if (!cs.GetStrokeColorSpaceResName().IsEmpty())
seen_resources["ColorSpace"].insert(cs.GetStrokeColorSpaceResName());
}

CPDF_PageObjectHolder::RemovedResourceMap RemoveUnusedResources(
Expand DownExpand Up@@ -357,6 +394,25 @@ CPDF_PageContentGenerator::GenerateModifiedStreams() {
all_dirty_streams.insert(marked_dirty_streams.begin(),
marked_dirty_streams.end());

// --- embedpdf: if anything is dirty, regenerate *all* page content streams.
// Rationale: CTM / graphics-state handoff between streams means rewriting
// only a subset can leave the concatenated effect inconsistent.
if (!all_dirty_streams.empty()) {
int32_t last_index = -1;
if (RetainPtr<const CPDF_Object> contents =
obj_holder_->GetDict()->GetObjectFor(pdfium::page_object::kContents)) {
if (const CPDF_Array* arr = contents->AsArray()) {
last_index = static_cast<int32_t>(arr->size()) - 1;
} else if (contents->IsStream()) {
last_index = 0;
}
}
for (int32_t i = 0; i <= last_index; ++i) {
all_dirty_streams.insert(i);
}
}
// --- end embedpdf

// Start regenerating dirty streams.
std::map<int32_t, fxcrt::ostringstream> streams;
std::set<int32_t> empty_streams;
Expand DownExpand Up@@ -510,6 +566,109 @@ void CPDF_PageContentGenerator::UpdateResourcesDict() {
obj_holder_->all_removed_resources_map());
}

ByteString CPDF_PageContentGenerator::RealizeColorSpaceObject(
const CPDF_ColorSpace* cs) {
if (!cs) return ByteString();

const auto fam = cs->GetFamily();
if (fam == CPDF_ColorSpace::Family::kDeviceGray ||
fam == CPDF_ColorSpace::Family::kDeviceRGB ||
fam == CPDF_ColorSpace::Family::kDeviceCMYK) {
return ByteString(); // device spaces don't need a resource
}

if (fam == CPDF_ColorSpace::Family::kICCBased) {
RetainPtr<CPDF_IccProfile> profile = cs->GetIccProfile();
if (!profile) return ByteString();

RetainPtr<const CPDF_StreamAcc> acc = profile->GetStreamAcc();
if (!acc)
return ByteString();
RetainPtr<const CPDF_Stream> icc = acc->GetStream();
if (!icc)
return ByteString();

// Stable cache key based on stream objnum
ByteString key = ByteString::Format("ICCB:%u", icc->GetObjNum());
if (auto hit = obj_holder_->ColorSpaceMapSearch(key))
return *hit;

// IMPORTANT: make array indirect
RetainPtr<CPDF_Array> arr = document_->NewIndirect<CPDF_Array>();
arr->AppendNew<CPDF_Name>("ICCBased");
arr->AppendNew<CPDF_Reference>(document_, icc->GetObjNum());

ByteString name = RealizeResource(arr.Get(), "ColorSpace");
obj_holder_->ColorSpaceMapInsert(key, name);
return name;
}

// (CalGray/CalRGB/Lab/Separation/DeviceN can be added later)
return ByteString();
}

bool CPDF_PageContentGenerator::EmitColor(fxcrt::ostringstream& buf,
const CPDF_Color* color,
bool is_stroke,
CPDF_PageObject* owner) {
if (!color) return false;

if (color->IsColorSpaceGray()) {
auto comps = color->GetRawNonPatternComps();
if (comps.size() == 1) {
WriteFloat(buf, comps[0]) << (is_stroke ? " G " : " g ");
// device space → clear any remembered resource name
if (is_stroke) owner->mutable_color_state().SetStrokeColorSpaceResName({});
else owner->mutable_color_state().SetFillColorSpaceResName({});
return true;
}
return false;
}

if (color->IsColorSpaceRGB()) {
auto rgb = color->GetRGB();
if (!rgb) return false;
WriteFloat(buf, rgb->red) << " ";
WriteFloat(buf, rgb->green) << " ";
WriteFloat(buf, rgb->blue) << (is_stroke ? " RG " : " rg ");
if (is_stroke) owner->mutable_color_state().SetStrokeColorSpaceResName({});
else owner->mutable_color_state().SetFillColorSpaceResName({});
return true;
}

if (color->IsColorSpaceCMYK()) {
auto comps = color->GetRawNonPatternComps(); // expect 4
if (comps.size() == 4) {
WriteFloat(buf, comps[0]) << " ";
WriteFloat(buf, comps[1]) << " ";
WriteFloat(buf, comps[2]) << " ";
WriteFloat(buf, comps[3]) << (is_stroke ? " K " : " k ");
if (is_stroke) owner->mutable_color_state().SetStrokeColorSpaceResName({});
else owner->mutable_color_state().SetFillColorSpaceResName({});
return true;
}
return false;
}

// Non-device: realize resource + scn/SCN
const CPDF_ColorSpace* cs = color->GetColorSpace();
ByteString cs_name = RealizeColorSpaceObject(cs);
if (cs_name.IsEmpty()) return false;

if (is_stroke) owner->mutable_color_state().SetStrokeColorSpaceResName(cs_name);
else owner->mutable_color_state().SetFillColorSpaceResName(cs_name);

buf << "/" << PDF_NameEncode(cs_name) << (is_stroke ? " CS " : " cs ");

auto comps = color->GetRawNonPatternComps();
for (size_t i = 0; i < comps.size(); ++i) {
if (i) buf << " ";
WriteFloat(buf, comps[i]);
}
buf << (is_stroke ? " SCN " : " scn ");
return true;
}

ByteString CPDF_PageContentGenerator::RealizeResource(
const CPDF_Object* pResource,
ByteStringView type) const {
Expand DownExpand Up@@ -819,11 +978,11 @@ void CPDF_PageContentGenerator::ProcessPath(fxcrt::ostringstream* buf,
void CPDF_PageContentGenerator::ProcessGraphics(fxcrt::ostringstream* buf,
CPDF_PageObject* pPageObj) {
*buf << "q ";
if (WriteColorToStream(*buf, pPageObj->color_state().GetFillColor())) {
*buf << " rg ";
if (const CPDF_Color* fill = pPageObj->color_state().GetFillColor()) {
EmitColor(*buf, fill, /*is_stroke=*/false, pPageObj);
}
if (WriteColorToStream(*buf, pPageObj->color_state().GetStrokeColor())) {
*buf << " RG ";
if (const CPDF_Color* stroke = pPageObj->color_state().GetStrokeColor()) {
EmitColor(*buf, stroke, /*is_stroke=*/true, pPageObj);
}
float line_width = pPageObj->graph_state().GetLineWidth();
if (line_width != 1.0f) {
Expand DownExpand Up@@ -909,7 +1068,7 @@ void CPDF_PageContentGenerator::ProcessGraphics(fxcrt::ostringstream* buf,

void CPDF_PageContentGenerator::ProcessDefaultGraphics(
fxcrt::ostringstream* buf) {
*buf << "0 0 0 RG 0 0 0 rg 1 w "
*buf << "1 w "
<< static_cast<int>(CFX_GraphStateData::LineCap::kButt) << " J "
<< static_cast<int>(CFX_GraphStateData::LineJoin::kMiter) << " j\n";
default_graphics_name_ = GetOrCreateDefaultGraphics();
Expand DownExpand Up@@ -948,39 +1107,69 @@ void CPDF_PageContentGenerator::ProcessText(fxcrt::ostringstream* buf,
ProcessGraphics(buf, pTextObj);
*buf << "BT ";

const CFX_Matrix& matrix = pTextObj->GetTextMatrix();
if (!matrix.IsIdentity()) {
WriteMatrix(*buf, matrix) << " Tm ";
// Separate translation (cm) from pure text matrix (Tm)
const CFX_Matrix& M = pTextObj->GetTextMatrix();
if (M.e != 0 || M.f != 0) {
WriteMatrix(*buf, CFX_Matrix(1, 0, 0, 1, M.e, M.f)) << " cm ";
}

CFX_Matrix TmNoTranslate(M.a, M.b, M.c, M.d, 0, 0);
if (!TmNoTranslate.IsIdentity()) {
WriteMatrix(*buf, TmNoTranslate) << " Tm ";
} else {
*buf << "1 0 0 1 0 0 Tm ";
}

// Ensure we have a font.
RetainPtr<CPDF_Font> font(pTextObj->GetFont());
if (!font) {
font = CPDF_Font::GetStockFont(document_, "Helvetica");
}

FontData data;
const CPDF_FontEncoding* pEncoding = nullptr;
if (font->IsType1Font()) {
data.type = "Type1";
pEncoding = font->AsType1Font()->GetEncoding();
} else if (font->IsTrueTypeFont()) {
data.type = "TrueType";
pEncoding = font->AsTrueTypeFont()->GetEncoding();
} else if (font->IsCIDFont()) {
data.type = "Type0";
} else {
return;
// --- Object-number keyed font resource binding ---
// Get the font dictionary; if it's inline, make it indirect so it has a stable objnum.
RetainPtr<const CPDF_Object> pFontDict = font->GetFontDict();
if (pFontDict && pFontDict->IsInline()) {
RetainPtr<CPDF_Object> clone = pFontDict->Clone();
document_->AddIndirectObject(clone);
pFontDict = std::move(clone);
}
data.baseFont = font->GetBaseFontName();

// Some (very old/odd) fonts may not expose a dict; fall back safely.
uint32_t font_objnum = pFontDict ? pFontDict->GetObjNum() : 0;

ByteString dict_name;
std::optional<ByteString> maybe_name = obj_holder_->FontsMapSearch(data);
if (maybe_name.has_value()) {
dict_name = std::move(maybe_name.value());
if (font_objnum) {
if (auto hit = obj_holder_->FontsByObjnumSearch(font_objnum)) {
dict_name = *hit;
} else {
// Realize this exact font object into Resources/Font and cache by objnum.
dict_name = RealizeResource(pFontDict.Get(), "Font");
obj_holder_->FontsByObjnumInsert(font_objnum, dict_name);
}
} else {
RetainPtr<const CPDF_Object> pIndirectFont = font->GetFontDict();
if (pIndirectFont->IsInline()) {
// In this case we assume it must be a standard font
// Last-resort path (should be rare): name by (type, base name) like before.
FontData data;
const CPDF_FontEncoding* pEncoding = nullptr;
if (font->IsType1Font()) {
data.type = "Type1";
pEncoding = font->AsType1Font()->GetEncoding();
} else if (font->IsTrueTypeFont()) {
data.type = "TrueType";
pEncoding = font->AsTrueTypeFont()->GetEncoding();
} else if (font->IsCIDFont()) {
data.type = "Type0";
} else {
*buf << "ET"; // bail out cleanly
EndProcessGraphics(*buf);
return;
}
data.baseFont = font->GetBaseFontName();

if (auto hit = obj_holder_->FontsMapSearch(data)) {
dict_name = *hit;
} else {
// Build a minimal indirect font dict (same as your old code).
auto font_dict = pdfium::MakeRetain<CPDF_Dictionary>();
font_dict->SetNewFor<CPDF_Name>("Type", "Font");
font_dict->SetNewFor<CPDF_Name>("Subtype", data.type);
Expand All@@ -990,22 +1179,34 @@ void CPDF_PageContentGenerator::ProcessText(fxcrt::ostringstream* buf,
pEncoding->Realize(document_->GetByteStringPool()));
}
document_->AddIndirectObject(font_dict);
pIndirectFont = std::move(font_dict);
dict_name = RealizeResource(std::move(font_dict), "Font");
obj_holder_->FontsMapInsert(data, dict_name);
}
dict_name = RealizeResource(std::move(pIndirectFont), "Font");
obj_holder_->FontsMapInsert(data, dict_name);
}

pTextObj->SetResourceName(dict_name);

*buf << "/" << PDF_NameEncode(dict_name) << " ";
WriteFloat(*buf, pTextObj->GetFontSize()) << " Tf ";
*buf << static_cast<int>(pTextObj->GetTextRenderMode()) << " Tr ";
ByteString text;
for (uint32_t charcode : pTextObj->GetCharCodes()) {
if (charcode != CPDF_Font::kInvalidCharCode) {
font->AppendChar(&text, charcode);

const float tc = pTextObj->GetCharSpace();
const float tw = pTextObj->GetWordSpace();

if (tc != 0.0f) WriteFloat(*buf, tc) << " Tc ";
if (tw != 0.0f) WriteFloat(*buf, tw) << " Tw ";

if (TextObjectNeedsTJ(pTextObj)) {
WriteTextAsTJ(*buf, pTextObj, font.Get());
*buf << " ET";
} else {
ByteString text;
for (uint32_t charcode : pTextObj->GetCharCodes()) {
if (charcode != CPDF_Font::kInvalidCharCode)
font->AppendChar(&text, charcode);
}
*buf << PDF_HexEncodeString(text.AsStringView()) << " Tj ET";
}
*buf << PDF_HexEncodeString(text.AsStringView()) << " Tj ET";

EndProcessGraphics(*buf);
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions core/fpdfapi/edit/BUILD.gn
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,6 +21,8 @@ source_set("edit") {
"cpdf_pageorganizer.h",
"cpdf_stringarchivestream.cpp",
"cpdf_stringarchivestream.h",
"cpdf_text_redactor.cpp",
"cpdf_text_redactor.h",
]
configs += [
"../../../:pdfium_strict_config",
Expand Down
295 changes: 248 additions & 47 deletions core/fpdfapi/edit/cpdf_pagecontentgenerator.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -30,6 +30,9 @@
#include "core/fpdfapi/page/cpdf_path.h"
#include "core/fpdfapi/page/cpdf_pathobject.h"
#include "core/fpdfapi/page/cpdf_textobject.h"
#include "core/fpdfapi/page/cpdf_color.h"
#include "core/fpdfapi/page/cpdf_colorspace.h"
#include "core/fpdfapi/page/cpdf_iccprofile.h"
#include "core/fpdfapi/parser/cpdf_array.h"
#include "core/fpdfapi/parser/cpdf_dictionary.h"
#include "core/fpdfapi/parser/cpdf_document.h"
Expand All@@ -53,27 +56,56 @@ namespace {
// - ColorSpace
// - Pattern
// - Shading
constexpr const char* kResourceKeys[] = {"ExtGState", "Font", "XObject"};
constexpr const char* kResourceKeys[] = {"ExtGState", "Font", "XObject", "ColorSpace"};

// Key: The resource type.
// Value: The resource names of a given type.
using ResourcesMap = std::map<ByteString, std::set<ByteString>>;

// Returns whether it wrote to `buf` or not.
bool WriteColorToStream(fxcrt::ostringstream& buf, const CPDF_Color* color) {
if (!color || (!color->IsColorSpaceRGB() && !color->IsColorSpaceGray())) {
return false;
bool TextObjectNeedsTJ(const CPDF_TextObject* obj) {
// We don’t have a public accessor for char_codes_, but we can reuse CountItems()
// and GetItemInfo(i). GetItemInfo() gives us char_code_ and (for vert writing)
// origin_. We only need to see if any item has the sentinel.
for (size_t i = 0, n = obj->CountItems(); i < n; ++i) {
auto it = obj->GetItemInfo(i);
if (it.char_code_ == CPDF_Font::kInvalidCharCode)
return true;
}
return false;
}

std::optional<FX_RGB_STRUCT<float>> colors = color->GetRGB();
if (!colors.has_value()) {
return false;
void WriteTextAsTJ(fxcrt::ostringstream& buf,
CPDF_TextObject* obj,
CPDF_Font* font) {
buf << "[ ";
ByteString hexChunk;

for (size_t i = 0, n = obj->CountItems(); i < n; ++i) {
CPDF_TextObject::Item it = obj->GetItemInfo(i);

if (it.char_code_ == CPDF_Font::kInvalidCharCode) {
if (!hexChunk.IsEmpty()) {
buf << PDF_HexEncodeString(hexChunk.AsStringView()) << " ";
hexChunk.clear();
}
float thousandths = 0.0f;
if (obj->GetSeparatorAdjustment(i, &thousandths)) {
// TJ numbers are interpreted as “subtract this from the text position”,
// which matches how CalcPositionDataInternal() used the stored value:
// curpos -= (thousandths * fontSize)/1000. So we emit the value as-is.
WriteFloat(buf, thousandths);
buf << " ";
}
continue;
}

font->AppendChar(&hexChunk, it.char_code_);
}

WriteFloat(buf, colors.value().red) << " ";
WriteFloat(buf, colors.value().green) << " ";
WriteFloat(buf, colors.value().blue);
return true;
if (!hexChunk.IsEmpty()) {
buf << PDF_HexEncodeString(hexChunk.AsStringView()) << " ";
}
buf << "] TJ";
}

// Balances the "q" operator ProcessGraphics() emitted.
Expand DownExpand Up@@ -103,6 +135,11 @@ void RecordPageObjectResourceUsage(const CPDF_PageObject* page_object,
CHECK(!name.IsEmpty());
seen_resources["ExtGState"].insert(name);
}
const CPDF_ColorState& cs = page_object->color_state();
if (!cs.GetFillColorSpaceResName().IsEmpty())
seen_resources["ColorSpace"].insert(cs.GetFillColorSpaceResName());
if (!cs.GetStrokeColorSpaceResName().IsEmpty())
seen_resources["ColorSpace"].insert(cs.GetStrokeColorSpaceResName());
}

CPDF_PageObjectHolder::RemovedResourceMap RemoveUnusedResources(
Expand DownExpand Up@@ -357,6 +394,25 @@ CPDF_PageContentGenerator::GenerateModifiedStreams() {
all_dirty_streams.insert(marked_dirty_streams.begin(),
marked_dirty_streams.end());

// --- embedpdf: if anything is dirty, regenerate *all* page content streams.
// Rationale: CTM / graphics-state handoff between streams means rewriting
// only a subset can leave the concatenated effect inconsistent.
if (!all_dirty_streams.empty()) {
int32_t last_index = -1;
if (RetainPtr<const CPDF_Object> contents =
obj_holder_->GetDict()->GetObjectFor(pdfium::page_object::kContents)) {
if (const CPDF_Array* arr = contents->AsArray()) {
last_index = static_cast<int32_t>(arr->size()) - 1;
} else if (contents->IsStream()) {
last_index = 0;
}
}
for (int32_t i = 0; i <= last_index; ++i) {
all_dirty_streams.insert(i);
}
}
// --- end embedpdf

// Start regenerating dirty streams.
std::map<int32_t, fxcrt::ostringstream> streams;
std::set<int32_t> empty_streams;
Expand DownExpand Up@@ -510,6 +566,109 @@ void CPDF_PageContentGenerator::UpdateResourcesDict() {
obj_holder_->all_removed_resources_map());
}

ByteString CPDF_PageContentGenerator::RealizeColorSpaceObject(
const CPDF_ColorSpace* cs) {
if (!cs) return ByteString();

const auto fam = cs->GetFamily();
if (fam == CPDF_ColorSpace::Family::kDeviceGray ||
fam == CPDF_ColorSpace::Family::kDeviceRGB ||
fam == CPDF_ColorSpace::Family::kDeviceCMYK) {
return ByteString(); // device spaces don't need a resource
}

if (fam == CPDF_ColorSpace::Family::kICCBased) {
RetainPtr<CPDF_IccProfile> profile = cs->GetIccProfile();
if (!profile) return ByteString();

RetainPtr<const CPDF_StreamAcc> acc = profile->GetStreamAcc();
if (!acc)
return ByteString();
RetainPtr<const CPDF_Stream> icc = acc->GetStream();
if (!icc)
return ByteString();

// Stable cache key based on stream objnum
ByteString key = ByteString::Format("ICCB:%u", icc->GetObjNum());
if (auto hit = obj_holder_->ColorSpaceMapSearch(key))
return *hit;

// IMPORTANT: make array indirect
RetainPtr<CPDF_Array> arr = document_->NewIndirect<CPDF_Array>();
arr->AppendNew<CPDF_Name>("ICCBased");
arr->AppendNew<CPDF_Reference>(document_, icc->GetObjNum());

ByteString name = RealizeResource(arr.Get(), "ColorSpace");
obj_holder_->ColorSpaceMapInsert(key, name);
return name;
}

// (CalGray/CalRGB/Lab/Separation/DeviceN can be added later)
return ByteString();
}

bool CPDF_PageContentGenerator::EmitColor(fxcrt::ostringstream& buf,
const CPDF_Color* color,
bool is_stroke,
CPDF_PageObject* owner) {
if (!color) return false;

if (color->IsColorSpaceGray()) {
auto comps = color->GetRawNonPatternComps();
if (comps.size() == 1) {
WriteFloat(buf, comps[0]) << (is_stroke ? " G " : " g ");
// device space → clear any remembered resource name
if (is_stroke) owner->mutable_color_state().SetStrokeColorSpaceResName({});
else owner->mutable_color_state().SetFillColorSpaceResName({});
return true;
}
return false;
}

if (color->IsColorSpaceRGB()) {
auto rgb = color->GetRGB();
if (!rgb) return false;
WriteFloat(buf, rgb->red) << " ";
WriteFloat(buf, rgb->green) << " ";
WriteFloat(buf, rgb->blue) << (is_stroke ? " RG " : " rg ");
if (is_stroke) owner->mutable_color_state().SetStrokeColorSpaceResName({});
else owner->mutable_color_state().SetFillColorSpaceResName({});
return true;
}

if (color->IsColorSpaceCMYK()) {
auto comps = color->GetRawNonPatternComps(); // expect 4
if (comps.size() == 4) {
WriteFloat(buf, comps[0]) << " ";
WriteFloat(buf, comps[1]) << " ";
WriteFloat(buf, comps[2]) << " ";
WriteFloat(buf, comps[3]) << (is_stroke ? " K " : " k ");
if (is_stroke) owner->mutable_color_state().SetStrokeColorSpaceResName({});
else owner->mutable_color_state().SetFillColorSpaceResName({});
return true;
}
return false;
}

// Non-device: realize resource + scn/SCN
const CPDF_ColorSpace* cs = color->GetColorSpace();
ByteString cs_name = RealizeColorSpaceObject(cs);
if (cs_name.IsEmpty()) return false;

if (is_stroke) owner->mutable_color_state().SetStrokeColorSpaceResName(cs_name);
else owner->mutable_color_state().SetFillColorSpaceResName(cs_name);

buf << "/" << PDF_NameEncode(cs_name) << (is_stroke ? " CS " : " cs ");

auto comps = color->GetRawNonPatternComps();
for (size_t i = 0; i < comps.size(); ++i) {
if (i) buf << " ";
WriteFloat(buf, comps[i]);
}
buf << (is_stroke ? " SCN " : " scn ");
return true;
}

ByteString CPDF_PageContentGenerator::RealizeResource(
const CPDF_Object* pResource,
ByteStringView type) const {
Expand DownExpand Up@@ -819,11 +978,11 @@ void CPDF_PageContentGenerator::ProcessPath(fxcrt::ostringstream* buf,
void CPDF_PageContentGenerator::ProcessGraphics(fxcrt::ostringstream* buf,
CPDF_PageObject* pPageObj) {
*buf << "q ";
if (WriteColorToStream(*buf, pPageObj->color_state().GetFillColor())) {
*buf << " rg ";
if (const CPDF_Color* fill = pPageObj->color_state().GetFillColor()) {
EmitColor(*buf, fill, /*is_stroke=*/false, pPageObj);
}
if (WriteColorToStream(*buf, pPageObj->color_state().GetStrokeColor())) {
*buf << " RG ";
if (const CPDF_Color* stroke = pPageObj->color_state().GetStrokeColor()) {
EmitColor(*buf, stroke, /*is_stroke=*/true, pPageObj);
}
float line_width = pPageObj->graph_state().GetLineWidth();
if (line_width != 1.0f) {
Expand DownExpand Up@@ -909,7 +1068,7 @@ void CPDF_PageContentGenerator::ProcessGraphics(fxcrt::ostringstream* buf,

void CPDF_PageContentGenerator::ProcessDefaultGraphics(
fxcrt::ostringstream* buf) {
*buf << "0 0 0 RG 0 0 0 rg 1 w "
*buf << "1 w "
<< static_cast<int>(CFX_GraphStateData::LineCap::kButt) << " J "
<< static_cast<int>(CFX_GraphStateData::LineJoin::kMiter) << " j\n";
default_graphics_name_ = GetOrCreateDefaultGraphics();
Expand DownExpand Up@@ -948,39 +1107,69 @@ void CPDF_PageContentGenerator::ProcessText(fxcrt::ostringstream* buf,
ProcessGraphics(buf, pTextObj);
*buf << "BT ";

const CFX_Matrix& matrix = pTextObj->GetTextMatrix();
if (!matrix.IsIdentity()) {
WriteMatrix(*buf, matrix) << " Tm ";
// Separate translation (cm) from pure text matrix (Tm)
const CFX_Matrix& M = pTextObj->GetTextMatrix();
if (M.e != 0 || M.f != 0) {
WriteMatrix(*buf, CFX_Matrix(1, 0, 0, 1, M.e, M.f)) << " cm ";
}

CFX_Matrix TmNoTranslate(M.a, M.b, M.c, M.d, 0, 0);
if (!TmNoTranslate.IsIdentity()) {
WriteMatrix(*buf, TmNoTranslate) << " Tm ";
} else {
*buf << "1 0 0 1 0 0 Tm ";
}

// Ensure we have a font.
RetainPtr<CPDF_Font> font(pTextObj->GetFont());
if (!font) {
font = CPDF_Font::GetStockFont(document_, "Helvetica");
}

FontData data;
const CPDF_FontEncoding* pEncoding = nullptr;
if (font->IsType1Font()) {
data.type = "Type1";
pEncoding = font->AsType1Font()->GetEncoding();
} else if (font->IsTrueTypeFont()) {
data.type = "TrueType";
pEncoding = font->AsTrueTypeFont()->GetEncoding();
} else if (font->IsCIDFont()) {
data.type = "Type0";
} else {
return;
// --- Object-number keyed font resource binding ---
// Get the font dictionary; if it's inline, make it indirect so it has a stable objnum.
RetainPtr<const CPDF_Object> pFontDict = font->GetFontDict();
if (pFontDict && pFontDict->IsInline()) {
RetainPtr<CPDF_Object> clone = pFontDict->Clone();
document_->AddIndirectObject(clone);
pFontDict = std::move(clone);
}
data.baseFont = font->GetBaseFontName();

// Some (very old/odd) fonts may not expose a dict; fall back safely.
uint32_t font_objnum = pFontDict ? pFontDict->GetObjNum() : 0;

ByteString dict_name;
std::optional<ByteString> maybe_name = obj_holder_->FontsMapSearch(data);
if (maybe_name.has_value()) {
dict_name = std::move(maybe_name.value());
if (font_objnum) {
if (auto hit = obj_holder_->FontsByObjnumSearch(font_objnum)) {
dict_name = *hit;
} else {
// Realize this exact font object into Resources/Font and cache by objnum.
dict_name = RealizeResource(pFontDict.Get(), "Font");
obj_holder_->FontsByObjnumInsert(font_objnum, dict_name);
}
} else {
RetainPtr<const CPDF_Object> pIndirectFont = font->GetFontDict();
if (pIndirectFont->IsInline()) {
// In this case we assume it must be a standard font
// Last-resort path (should be rare): name by (type, base name) like before.
FontData data;
const CPDF_FontEncoding* pEncoding = nullptr;
if (font->IsType1Font()) {
data.type = "Type1";
pEncoding = font->AsType1Font()->GetEncoding();
} else if (font->IsTrueTypeFont()) {
data.type = "TrueType";
pEncoding = font->AsTrueTypeFont()->GetEncoding();
} else if (font->IsCIDFont()) {
data.type = "Type0";
} else {
*buf << "ET"; // bail out cleanly
EndProcessGraphics(*buf);
return;
}
data.baseFont = font->GetBaseFontName();

if (auto hit = obj_holder_->FontsMapSearch(data)) {
dict_name = *hit;
} else {
// Build a minimal indirect font dict (same as your old code).
auto font_dict = pdfium::MakeRetain<CPDF_Dictionary>();
font_dict->SetNewFor<CPDF_Name>("Type", "Font");
font_dict->SetNewFor<CPDF_Name>("Subtype", data.type);
Expand All@@ -990,22 +1179,34 @@ void CPDF_PageContentGenerator::ProcessText(fxcrt::ostringstream* buf,
pEncoding->Realize(document_->GetByteStringPool()));
}
document_->AddIndirectObject(font_dict);
pIndirectFont = std::move(font_dict);
dict_name = RealizeResource(std::move(font_dict), "Font");
obj_holder_->FontsMapInsert(data, dict_name);
}
dict_name = RealizeResource(std::move(pIndirectFont), "Font");
obj_holder_->FontsMapInsert(data, dict_name);
}

pTextObj->SetResourceName(dict_name);

*buf << "/" << PDF_NameEncode(dict_name) << " ";
WriteFloat(*buf, pTextObj->GetFontSize()) << " Tf ";
*buf << static_cast<int>(pTextObj->GetTextRenderMode()) << " Tr ";
ByteString text;
for (uint32_t charcode : pTextObj->GetCharCodes()) {
if (charcode != CPDF_Font::kInvalidCharCode) {
font->AppendChar(&text, charcode);

const float tc = pTextObj->GetCharSpace();
const float tw = pTextObj->GetWordSpace();

if (tc != 0.0f) WriteFloat(*buf, tc) << " Tc ";
if (tw != 0.0f) WriteFloat(*buf, tw) << " Tw ";

if (TextObjectNeedsTJ(pTextObj)) {
WriteTextAsTJ(*buf, pTextObj, font.Get());
*buf << " ET";
} else {
ByteString text;
for (uint32_t charcode : pTextObj->GetCharCodes()) {
if (charcode != CPDF_Font::kInvalidCharCode)
font->AppendChar(&text, charcode);
}
*buf << PDF_HexEncodeString(text.AsStringView()) << " Tj ET";
}
*buf << PDF_HexEncodeString(text.AsStringView()) << " Tj ET";

EndProcessGraphics(*buf);
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions core/fpdfapi/edit/BUILD.gn
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,6 +21,8 @@ source_set("edit") {
"cpdf_pageorganizer.h",
"cpdf_stringarchivestream.cpp",
"cpdf_stringarchivestream.h",
"cpdf_text_redactor.cpp",
"cpdf_text_redactor.h",
]
configs += [
"../../../:pdfium_strict_config",
Expand Down
295 changes: 248 additions & 47 deletions core/fpdfapi/edit/cpdf_pagecontentgenerator.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -30,6 +30,9 @@
#include "core/fpdfapi/page/cpdf_path.h"
#include "core/fpdfapi/page/cpdf_pathobject.h"
#include "core/fpdfapi/page/cpdf_textobject.h"
#include "core/fpdfapi/page/cpdf_color.h"
#include "core/fpdfapi/page/cpdf_colorspace.h"
#include "core/fpdfapi/page/cpdf_iccprofile.h"
#include "core/fpdfapi/parser/cpdf_array.h"
#include "core/fpdfapi/parser/cpdf_dictionary.h"
#include "core/fpdfapi/parser/cpdf_document.h"
Expand All@@ -53,27 +56,56 @@ namespace {
// - ColorSpace
// - Pattern
// - Shading
constexpr const char* kResourceKeys[] = {"ExtGState", "Font", "XObject"};
constexpr const char* kResourceKeys[] = {"ExtGState", "Font", "XObject", "ColorSpace"};

// Key: The resource type.
// Value: The resource names of a given type.
using ResourcesMap = std::map<ByteString, std::set<ByteString>>;

// Returns whether it wrote to `buf` or not.
bool WriteColorToStream(fxcrt::ostringstream& buf, const CPDF_Color* color) {
if (!color || (!color->IsColorSpaceRGB() && !color->IsColorSpaceGray())) {
return false;
bool TextObjectNeedsTJ(const CPDF_TextObject* obj) {
// We don’t have a public accessor for char_codes_, but we can reuse CountItems()
// and GetItemInfo(i). GetItemInfo() gives us char_code_ and (for vert writing)
// origin_. We only need to see if any item has the sentinel.
for (size_t i = 0, n = obj->CountItems(); i < n; ++i) {
auto it = obj->GetItemInfo(i);
if (it.char_code_ == CPDF_Font::kInvalidCharCode)
return true;
}
return false;
}

std::optional<FX_RGB_STRUCT<float>> colors = color->GetRGB();
if (!colors.has_value()) {
return false;
void WriteTextAsTJ(fxcrt::ostringstream& buf,
CPDF_TextObject* obj,
CPDF_Font* font) {
buf << "[ ";
ByteString hexChunk;

for (size_t i = 0, n = obj->CountItems(); i < n; ++i) {
CPDF_TextObject::Item it = obj->GetItemInfo(i);

if (it.char_code_ == CPDF_Font::kInvalidCharCode) {
if (!hexChunk.IsEmpty()) {
buf << PDF_HexEncodeString(hexChunk.AsStringView()) << " ";
hexChunk.clear();
}
float thousandths = 0.0f;
if (obj->GetSeparatorAdjustment(i, &thousandths)) {
// TJ numbers are interpreted as “subtract this from the text position”,
// which matches how CalcPositionDataInternal() used the stored value:
// curpos -= (thousandths * fontSize)/1000. So we emit the value as-is.
WriteFloat(buf, thousandths);
buf << " ";
}
continue;
}

font->AppendChar(&hexChunk, it.char_code_);
}

WriteFloat(buf, colors.value().red) << " ";
WriteFloat(buf, colors.value().green) << " ";
WriteFloat(buf, colors.value().blue);
return true;
if (!hexChunk.IsEmpty()) {
buf << PDF_HexEncodeString(hexChunk.AsStringView()) << " ";
}
buf << "] TJ";
}

// Balances the "q" operator ProcessGraphics() emitted.
Expand DownExpand Up@@ -103,6 +135,11 @@ void RecordPageObjectResourceUsage(const CPDF_PageObject* page_object,
CHECK(!name.IsEmpty());
seen_resources["ExtGState"].insert(name);
}
const CPDF_ColorState& cs = page_object->color_state();
if (!cs.GetFillColorSpaceResName().IsEmpty())
seen_resources["ColorSpace"].insert(cs.GetFillColorSpaceResName());
if (!cs.GetStrokeColorSpaceResName().IsEmpty())
seen_resources["ColorSpace"].insert(cs.GetStrokeColorSpaceResName());
}

CPDF_PageObjectHolder::RemovedResourceMap RemoveUnusedResources(
Expand DownExpand Up@@ -357,6 +394,25 @@ CPDF_PageContentGenerator::GenerateModifiedStreams() {
all_dirty_streams.insert(marked_dirty_streams.begin(),
marked_dirty_streams.end());

// --- embedpdf: if anything is dirty, regenerate *all* page content streams.
// Rationale: CTM / graphics-state handoff between streams means rewriting
// only a subset can leave the concatenated effect inconsistent.
if (!all_dirty_streams.empty()) {
int32_t last_index = -1;
if (RetainPtr<const CPDF_Object> contents =
obj_holder_->GetDict()->GetObjectFor(pdfium::page_object::kContents)) {
if (const CPDF_Array* arr = contents->AsArray()) {
last_index = static_cast<int32_t>(arr->size()) - 1;
} else if (contents->IsStream()) {
last_index = 0;
}
}
for (int32_t i = 0; i <= last_index; ++i) {
all_dirty_streams.insert(i);
}
}
// --- end embedpdf

// Start regenerating dirty streams.
std::map<int32_t, fxcrt::ostringstream> streams;
std::set<int32_t> empty_streams;
Expand DownExpand Up@@ -510,6 +566,109 @@ void CPDF_PageContentGenerator::UpdateResourcesDict() {
obj_holder_->all_removed_resources_map());
}

ByteString CPDF_PageContentGenerator::RealizeColorSpaceObject(
const CPDF_ColorSpace* cs) {
if (!cs) return ByteString();

const auto fam = cs->GetFamily();
if (fam == CPDF_ColorSpace::Family::kDeviceGray ||
fam == CPDF_ColorSpace::Family::kDeviceRGB ||
fam == CPDF_ColorSpace::Family::kDeviceCMYK) {
return ByteString(); // device spaces don't need a resource
}

if (fam == CPDF_ColorSpace::Family::kICCBased) {
RetainPtr<CPDF_IccProfile> profile = cs->GetIccProfile();
if (!profile) return ByteString();

RetainPtr<const CPDF_StreamAcc> acc = profile->GetStreamAcc();
if (!acc)
return ByteString();
RetainPtr<const CPDF_Stream> icc = acc->GetStream();
if (!icc)
return ByteString();

// Stable cache key based on stream objnum
ByteString key = ByteString::Format("ICCB:%u", icc->GetObjNum());
if (auto hit = obj_holder_->ColorSpaceMapSearch(key))
return *hit;

// IMPORTANT: make array indirect
RetainPtr<CPDF_Array> arr = document_->NewIndirect<CPDF_Array>();
arr->AppendNew<CPDF_Name>("ICCBased");
arr->AppendNew<CPDF_Reference>(document_, icc->GetObjNum());

ByteString name = RealizeResource(arr.Get(), "ColorSpace");
obj_holder_->ColorSpaceMapInsert(key, name);
return name;
}

// (CalGray/CalRGB/Lab/Separation/DeviceN can be added later)
return ByteString();
}

bool CPDF_PageContentGenerator::EmitColor(fxcrt::ostringstream& buf,
const CPDF_Color* color,
bool is_stroke,
CPDF_PageObject* owner) {
if (!color) return false;

if (color->IsColorSpaceGray()) {
auto comps = color->GetRawNonPatternComps();
if (comps.size() == 1) {
WriteFloat(buf, comps[0]) << (is_stroke ? " G " : " g ");
// device space → clear any remembered resource name
if (is_stroke) owner->mutable_color_state().SetStrokeColorSpaceResName({});
else owner->mutable_color_state().SetFillColorSpaceResName({});
return true;
}
return false;
}

if (color->IsColorSpaceRGB()) {
auto rgb = color->GetRGB();
if (!rgb) return false;
WriteFloat(buf, rgb->red) << " ";
WriteFloat(buf, rgb->green) << " ";
WriteFloat(buf, rgb->blue) << (is_stroke ? " RG " : " rg ");
if (is_stroke) owner->mutable_color_state().SetStrokeColorSpaceResName({});
else owner->mutable_color_state().SetFillColorSpaceResName({});
return true;
}

if (color->IsColorSpaceCMYK()) {
auto comps = color->GetRawNonPatternComps(); // expect 4
if (comps.size() == 4) {
WriteFloat(buf, comps[0]) << " ";
WriteFloat(buf, comps[1]) << " ";
WriteFloat(buf, comps[2]) << " ";
WriteFloat(buf, comps[3]) << (is_stroke ? " K " : " k ");
if (is_stroke) owner->mutable_color_state().SetStrokeColorSpaceResName({});
else owner->mutable_color_state().SetFillColorSpaceResName({});
return true;
}
return false;
}

// Non-device: realize resource + scn/SCN
const CPDF_ColorSpace* cs = color->GetColorSpace();
ByteString cs_name = RealizeColorSpaceObject(cs);
if (cs_name.IsEmpty()) return false;

if (is_stroke) owner->mutable_color_state().SetStrokeColorSpaceResName(cs_name);
else owner->mutable_color_state().SetFillColorSpaceResName(cs_name);

buf << "/" << PDF_NameEncode(cs_name) << (is_stroke ? " CS " : " cs ");

auto comps = color->GetRawNonPatternComps();
for (size_t i = 0; i < comps.size(); ++i) {
if (i) buf << " ";
WriteFloat(buf, comps[i]);
}
buf << (is_stroke ? " SCN " : " scn ");
return true;
}

ByteString CPDF_PageContentGenerator::RealizeResource(
const CPDF_Object* pResource,
ByteStringView type) const {
Expand DownExpand Up@@ -819,11 +978,11 @@ void CPDF_PageContentGenerator::ProcessPath(fxcrt::ostringstream* buf,
void CPDF_PageContentGenerator::ProcessGraphics(fxcrt::ostringstream* buf,
CPDF_PageObject* pPageObj) {
*buf << "q ";
if (WriteColorToStream(*buf, pPageObj->color_state().GetFillColor())) {
*buf << " rg ";
if (const CPDF_Color* fill = pPageObj->color_state().GetFillColor()) {
EmitColor(*buf, fill, /*is_stroke=*/false, pPageObj);
}
if (WriteColorToStream(*buf, pPageObj->color_state().GetStrokeColor())) {
*buf << " RG ";
if (const CPDF_Color* stroke = pPageObj->color_state().GetStrokeColor()) {
EmitColor(*buf, stroke, /*is_stroke=*/true, pPageObj);
}
float line_width = pPageObj->graph_state().GetLineWidth();
if (line_width != 1.0f) {
Expand DownExpand Up@@ -909,7 +1068,7 @@ void CPDF_PageContentGenerator::ProcessGraphics(fxcrt::ostringstream* buf,

void CPDF_PageContentGenerator::ProcessDefaultGraphics(
fxcrt::ostringstream* buf) {
*buf << "0 0 0 RG 0 0 0 rg 1 w "
*buf << "1 w "
<< static_cast<int>(CFX_GraphStateData::LineCap::kButt) << " J "
<< static_cast<int>(CFX_GraphStateData::LineJoin::kMiter) << " j\n";
default_graphics_name_ = GetOrCreateDefaultGraphics();
Expand DownExpand Up@@ -948,39 +1107,69 @@ void CPDF_PageContentGenerator::ProcessText(fxcrt::ostringstream* buf,
ProcessGraphics(buf, pTextObj);
*buf << "BT ";

const CFX_Matrix& matrix = pTextObj->GetTextMatrix();
if (!matrix.IsIdentity()) {
WriteMatrix(*buf, matrix) << " Tm ";
// Separate translation (cm) from pure text matrix (Tm)
const CFX_Matrix& M = pTextObj->GetTextMatrix();
if (M.e != 0 || M.f != 0) {
WriteMatrix(*buf, CFX_Matrix(1, 0, 0, 1, M.e, M.f)) << " cm ";
}

CFX_Matrix TmNoTranslate(M.a, M.b, M.c, M.d, 0, 0);
if (!TmNoTranslate.IsIdentity()) {
WriteMatrix(*buf, TmNoTranslate) << " Tm ";
} else {
*buf << "1 0 0 1 0 0 Tm ";
}

// Ensure we have a font.
RetainPtr<CPDF_Font> font(pTextObj->GetFont());
if (!font) {
font = CPDF_Font::GetStockFont(document_, "Helvetica");
}

FontData data;
const CPDF_FontEncoding* pEncoding = nullptr;
if (font->IsType1Font()) {
data.type = "Type1";
pEncoding = font->AsType1Font()->GetEncoding();
} else if (font->IsTrueTypeFont()) {
data.type = "TrueType";
pEncoding = font->AsTrueTypeFont()->GetEncoding();
} else if (font->IsCIDFont()) {
data.type = "Type0";
} else {
return;
// --- Object-number keyed font resource binding ---
// Get the font dictionary; if it's inline, make it indirect so it has a stable objnum.
RetainPtr<const CPDF_Object> pFontDict = font->GetFontDict();
if (pFontDict && pFontDict->IsInline()) {
RetainPtr<CPDF_Object> clone = pFontDict->Clone();
document_->AddIndirectObject(clone);
pFontDict = std::move(clone);
}
data.baseFont = font->GetBaseFontName();

// Some (very old/odd) fonts may not expose a dict; fall back safely.
uint32_t font_objnum = pFontDict ? pFontDict->GetObjNum() : 0;

ByteString dict_name;
std::optional<ByteString> maybe_name = obj_holder_->FontsMapSearch(data);
if (maybe_name.has_value()) {
dict_name = std::move(maybe_name.value());
if (font_objnum) {
if (auto hit = obj_holder_->FontsByObjnumSearch(font_objnum)) {
dict_name = *hit;
} else {
// Realize this exact font object into Resources/Font and cache by objnum.
dict_name = RealizeResource(pFontDict.Get(), "Font");
obj_holder_->FontsByObjnumInsert(font_objnum, dict_name);
}
} else {
RetainPtr<const CPDF_Object> pIndirectFont = font->GetFontDict();
if (pIndirectFont->IsInline()) {
// In this case we assume it must be a standard font
// Last-resort path (should be rare): name by (type, base name) like before.
FontData data;
const CPDF_FontEncoding* pEncoding = nullptr;
if (font->IsType1Font()) {
data.type = "Type1";
pEncoding = font->AsType1Font()->GetEncoding();
} else if (font->IsTrueTypeFont()) {
data.type = "TrueType";
pEncoding = font->AsTrueTypeFont()->GetEncoding();
} else if (font->IsCIDFont()) {
data.type = "Type0";
} else {
*buf << "ET"; // bail out cleanly
EndProcessGraphics(*buf);
return;
}
data.baseFont = font->GetBaseFontName();

if (auto hit = obj_holder_->FontsMapSearch(data)) {
dict_name = *hit;
} else {
// Build a minimal indirect font dict (same as your old code).
auto font_dict = pdfium::MakeRetain<CPDF_Dictionary>();
font_dict->SetNewFor<CPDF_Name>("Type", "Font");
font_dict->SetNewFor<CPDF_Name>("Subtype", data.type);
Expand All@@ -990,22 +1179,34 @@ void CPDF_PageContentGenerator::ProcessText(fxcrt::ostringstream* buf,
pEncoding->Realize(document_->GetByteStringPool()));
}
document_->AddIndirectObject(font_dict);
pIndirectFont = std::move(font_dict);
dict_name = RealizeResource(std::move(font_dict), "Font");
obj_holder_->FontsMapInsert(data, dict_name);
}
dict_name = RealizeResource(std::move(pIndirectFont), "Font");
obj_holder_->FontsMapInsert(data, dict_name);
}

pTextObj->SetResourceName(dict_name);

*buf << "/" << PDF_NameEncode(dict_name) << " ";
WriteFloat(*buf, pTextObj->GetFontSize()) << " Tf ";
*buf << static_cast<int>(pTextObj->GetTextRenderMode()) << " Tr ";
ByteString text;
for (uint32_t charcode : pTextObj->GetCharCodes()) {
if (charcode != CPDF_Font::kInvalidCharCode) {
font->AppendChar(&text, charcode);

const float tc = pTextObj->GetCharSpace();
const float tw = pTextObj->GetWordSpace();

if (tc != 0.0f) WriteFloat(*buf, tc) << " Tc ";
if (tw != 0.0f) WriteFloat(*buf, tw) << " Tw ";

if (TextObjectNeedsTJ(pTextObj)) {
WriteTextAsTJ(*buf, pTextObj, font.Get());
*buf << " ET";
} else {
ByteString text;
for (uint32_t charcode : pTextObj->GetCharCodes()) {
if (charcode != CPDF_Font::kInvalidCharCode)
font->AppendChar(&text, charcode);
}
*buf << PDF_HexEncodeString(text.AsStringView()) << " Tj ET";
}
*buf << PDF_HexEncodeString(text.AsStringView()) << " Tj ET";

EndProcessGraphics(*buf);
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions core/fpdfapi/edit/BUILD.gn
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,6 +21,8 @@ source_set("edit") {
"cpdf_pageorganizer.h",
"cpdf_stringarchivestream.cpp",
"cpdf_stringarchivestream.h",
"cpdf_text_redactor.cpp",
"cpdf_text_redactor.h",
]
configs += [
"../../../:pdfium_strict_config",
Expand Down
295 changes: 248 additions & 47 deletions core/fpdfapi/edit/cpdf_pagecontentgenerator.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -30,6 +30,9 @@
#include "core/fpdfapi/page/cpdf_path.h"
#include "core/fpdfapi/page/cpdf_pathobject.h"
#include "core/fpdfapi/page/cpdf_textobject.h"
#include "core/fpdfapi/page/cpdf_color.h"
#include "core/fpdfapi/page/cpdf_colorspace.h"
#include "core/fpdfapi/page/cpdf_iccprofile.h"
#include "core/fpdfapi/parser/cpdf_array.h"
#include "core/fpdfapi/parser/cpdf_dictionary.h"
#include "core/fpdfapi/parser/cpdf_document.h"
Expand All@@ -53,27 +56,56 @@ namespace {
// - ColorSpace
// - Pattern
// - Shading
constexpr const char* kResourceKeys[] = {"ExtGState", "Font", "XObject"};
constexpr const char* kResourceKeys[] = {"ExtGState", "Font", "XObject", "ColorSpace"};

// Key: The resource type.
// Value: The resource names of a given type.
using ResourcesMap = std::map<ByteString, std::set<ByteString>>;

// Returns whether it wrote to `buf` or not.
bool WriteColorToStream(fxcrt::ostringstream& buf, const CPDF_Color* color) {
if (!color || (!color->IsColorSpaceRGB() && !color->IsColorSpaceGray())) {
return false;
bool TextObjectNeedsTJ(const CPDF_TextObject* obj) {
// We don’t have a public accessor for char_codes_, but we can reuse CountItems()
// and GetItemInfo(i). GetItemInfo() gives us char_code_ and (for vert writing)
// origin_. We only need to see if any item has the sentinel.
for (size_t i = 0, n = obj->CountItems(); i < n; ++i) {
auto it = obj->GetItemInfo(i);
if (it.char_code_ == CPDF_Font::kInvalidCharCode)
return true;
}
return false;
}

std::optional<FX_RGB_STRUCT<float>> colors = color->GetRGB();
if (!colors.has_value()) {
return false;
void WriteTextAsTJ(fxcrt::ostringstream& buf,
CPDF_TextObject* obj,
CPDF_Font* font) {
buf << "[ ";
ByteString hexChunk;

for (size_t i = 0, n = obj->CountItems(); i < n; ++i) {
CPDF_TextObject::Item it = obj->GetItemInfo(i);

if (it.char_code_ == CPDF_Font::kInvalidCharCode) {
if (!hexChunk.IsEmpty()) {
buf << PDF_HexEncodeString(hexChunk.AsStringView()) << " ";
hexChunk.clear();
}
float thousandths = 0.0f;
if (obj->GetSeparatorAdjustment(i, &thousandths)) {
// TJ numbers are interpreted as “subtract this from the text position”,
// which matches how CalcPositionDataInternal() used the stored value:
// curpos -= (thousandths * fontSize)/1000. So we emit the value as-is.
WriteFloat(buf, thousandths);
buf << " ";
}
continue;
}

font->AppendChar(&hexChunk, it.char_code_);
}

WriteFloat(buf, colors.value().red) << " ";
WriteFloat(buf, colors.value().green) << " ";
WriteFloat(buf, colors.value().blue);
return true;
if (!hexChunk.IsEmpty()) {
buf << PDF_HexEncodeString(hexChunk.AsStringView()) << " ";
}
buf << "] TJ";
}

// Balances the "q" operator ProcessGraphics() emitted.
Expand DownExpand Up@@ -103,6 +135,11 @@ void RecordPageObjectResourceUsage(const CPDF_PageObject* page_object,
CHECK(!name.IsEmpty());
seen_resources["ExtGState"].insert(name);
}
const CPDF_ColorState& cs = page_object->color_state();
if (!cs.GetFillColorSpaceResName().IsEmpty())
seen_resources["ColorSpace"].insert(cs.GetFillColorSpaceResName());
if (!cs.GetStrokeColorSpaceResName().IsEmpty())
seen_resources["ColorSpace"].insert(cs.GetStrokeColorSpaceResName());
}

CPDF_PageObjectHolder::RemovedResourceMap RemoveUnusedResources(
Expand DownExpand Up@@ -357,6 +394,25 @@ CPDF_PageContentGenerator::GenerateModifiedStreams() {
all_dirty_streams.insert(marked_dirty_streams.begin(),
marked_dirty_streams.end());

// --- embedpdf: if anything is dirty, regenerate *all* page content streams.
// Rationale: CTM / graphics-state handoff between streams means rewriting
// only a subset can leave the concatenated effect inconsistent.
if (!all_dirty_streams.empty()) {
int32_t last_index = -1;
if (RetainPtr<const CPDF_Object> contents =
obj_holder_->GetDict()->GetObjectFor(pdfium::page_object::kContents)) {
if (const CPDF_Array* arr = contents->AsArray()) {
last_index = static_cast<int32_t>(arr->size()) - 1;
} else if (contents->IsStream()) {
last_index = 0;
}
}
for (int32_t i = 0; i <= last_index; ++i) {
all_dirty_streams.insert(i);
}
}
// --- end embedpdf

// Start regenerating dirty streams.
std::map<int32_t, fxcrt::ostringstream> streams;
std::set<int32_t> empty_streams;
Expand DownExpand Up@@ -510,6 +566,109 @@ void CPDF_PageContentGenerator::UpdateResourcesDict() {
obj_holder_->all_removed_resources_map());
}

ByteString CPDF_PageContentGenerator::RealizeColorSpaceObject(
const CPDF_ColorSpace* cs) {
if (!cs) return ByteString();

const auto fam = cs->GetFamily();
if (fam == CPDF_ColorSpace::Family::kDeviceGray ||
fam == CPDF_ColorSpace::Family::kDeviceRGB ||
fam == CPDF_ColorSpace::Family::kDeviceCMYK) {
return ByteString(); // device spaces don't need a resource
}

if (fam == CPDF_ColorSpace::Family::kICCBased) {
RetainPtr<CPDF_IccProfile> profile = cs->GetIccProfile();
if (!profile) return ByteString();

RetainPtr<const CPDF_StreamAcc> acc = profile->GetStreamAcc();
if (!acc)
return ByteString();
RetainPtr<const CPDF_Stream> icc = acc->GetStream();
if (!icc)
return ByteString();

// Stable cache key based on stream objnum
ByteString key = ByteString::Format("ICCB:%u", icc->GetObjNum());
if (auto hit = obj_holder_->ColorSpaceMapSearch(key))
return *hit;

// IMPORTANT: make array indirect
RetainPtr<CPDF_Array> arr = document_->NewIndirect<CPDF_Array>();
arr->AppendNew<CPDF_Name>("ICCBased");
arr->AppendNew<CPDF_Reference>(document_, icc->GetObjNum());

ByteString name = RealizeResource(arr.Get(), "ColorSpace");
obj_holder_->ColorSpaceMapInsert(key, name);
return name;
}

// (CalGray/CalRGB/Lab/Separation/DeviceN can be added later)
return ByteString();
}

bool CPDF_PageContentGenerator::EmitColor(fxcrt::ostringstream& buf,
const CPDF_Color* color,
bool is_stroke,
CPDF_PageObject* owner) {
if (!color) return false;

if (color->IsColorSpaceGray()) {
auto comps = color->GetRawNonPatternComps();
if (comps.size() == 1) {
WriteFloat(buf, comps[0]) << (is_stroke ? " G " : " g ");
// device space → clear any remembered resource name
if (is_stroke) owner->mutable_color_state().SetStrokeColorSpaceResName({});
else owner->mutable_color_state().SetFillColorSpaceResName({});
return true;
}
return false;
}

if (color->IsColorSpaceRGB()) {
auto rgb = color->GetRGB();
if (!rgb) return false;
WriteFloat(buf, rgb->red) << " ";
WriteFloat(buf, rgb->green) << " ";
WriteFloat(buf, rgb->blue) << (is_stroke ? " RG " : " rg ");
if (is_stroke) owner->mutable_color_state().SetStrokeColorSpaceResName({});
else owner->mutable_color_state().SetFillColorSpaceResName({});
return true;
}

if (color->IsColorSpaceCMYK()) {
auto comps = color->GetRawNonPatternComps(); // expect 4
if (comps.size() == 4) {
WriteFloat(buf, comps[0]) << " ";
WriteFloat(buf, comps[1]) << " ";
WriteFloat(buf, comps[2]) << " ";
WriteFloat(buf, comps[3]) << (is_stroke ? " K " : " k ");
if (is_stroke) owner->mutable_color_state().SetStrokeColorSpaceResName({});
else owner->mutable_color_state().SetFillColorSpaceResName({});
return true;
}
return false;
}

// Non-device: realize resource + scn/SCN
const CPDF_ColorSpace* cs = color->GetColorSpace();
ByteString cs_name = RealizeColorSpaceObject(cs);
if (cs_name.IsEmpty()) return false;

if (is_stroke) owner->mutable_color_state().SetStrokeColorSpaceResName(cs_name);
else owner->mutable_color_state().SetFillColorSpaceResName(cs_name);

buf << "/" << PDF_NameEncode(cs_name) << (is_stroke ? " CS " : " cs ");

auto comps = color->GetRawNonPatternComps();
for (size_t i = 0; i < comps.size(); ++i) {
if (i) buf << " ";
WriteFloat(buf, comps[i]);
}
buf << (is_stroke ? " SCN " : " scn ");
return true;
}

ByteString CPDF_PageContentGenerator::RealizeResource(
const CPDF_Object* pResource,
ByteStringView type) const {
Expand DownExpand Up@@ -819,11 +978,11 @@ void CPDF_PageContentGenerator::ProcessPath(fxcrt::ostringstream* buf,
void CPDF_PageContentGenerator::ProcessGraphics(fxcrt::ostringstream* buf,
CPDF_PageObject* pPageObj) {
*buf << "q ";
if (WriteColorToStream(*buf, pPageObj->color_state().GetFillColor())) {
*buf << " rg ";
if (const CPDF_Color* fill = pPageObj->color_state().GetFillColor()) {
EmitColor(*buf, fill, /*is_stroke=*/false, pPageObj);
}
if (WriteColorToStream(*buf, pPageObj->color_state().GetStrokeColor())) {
*buf << " RG ";
if (const CPDF_Color* stroke = pPageObj->color_state().GetStrokeColor()) {
EmitColor(*buf, stroke, /*is_stroke=*/true, pPageObj);
}
float line_width = pPageObj->graph_state().GetLineWidth();
if (line_width != 1.0f) {
Expand DownExpand Up@@ -909,7 +1068,7 @@ void CPDF_PageContentGenerator::ProcessGraphics(fxcrt::ostringstream* buf,

void CPDF_PageContentGenerator::ProcessDefaultGraphics(
fxcrt::ostringstream* buf) {
*buf << "0 0 0 RG 0 0 0 rg 1 w "
*buf << "1 w "
<< static_cast<int>(CFX_GraphStateData::LineCap::kButt) << " J "
<< static_cast<int>(CFX_GraphStateData::LineJoin::kMiter) << " j\n";
default_graphics_name_ = GetOrCreateDefaultGraphics();
Expand DownExpand Up@@ -948,39 +1107,69 @@ void CPDF_PageContentGenerator::ProcessText(fxcrt::ostringstream* buf,
ProcessGraphics(buf, pTextObj);
*buf << "BT ";

const CFX_Matrix& matrix = pTextObj->GetTextMatrix();
if (!matrix.IsIdentity()) {
WriteMatrix(*buf, matrix) << " Tm ";
// Separate translation (cm) from pure text matrix (Tm)
const CFX_Matrix& M = pTextObj->GetTextMatrix();
if (M.e != 0 || M.f != 0) {
WriteMatrix(*buf, CFX_Matrix(1, 0, 0, 1, M.e, M.f)) << " cm ";
}

CFX_Matrix TmNoTranslate(M.a, M.b, M.c, M.d, 0, 0);
if (!TmNoTranslate.IsIdentity()) {
WriteMatrix(*buf, TmNoTranslate) << " Tm ";
} else {
*buf << "1 0 0 1 0 0 Tm ";
}

// Ensure we have a font.
RetainPtr<CPDF_Font> font(pTextObj->GetFont());
if (!font) {
font = CPDF_Font::GetStockFont(document_, "Helvetica");
}

FontData data;
const CPDF_FontEncoding* pEncoding = nullptr;
if (font->IsType1Font()) {
data.type = "Type1";
pEncoding = font->AsType1Font()->GetEncoding();
} else if (font->IsTrueTypeFont()) {
data.type = "TrueType";
pEncoding = font->AsTrueTypeFont()->GetEncoding();
} else if (font->IsCIDFont()) {
data.type = "Type0";
} else {
return;
// --- Object-number keyed font resource binding ---
// Get the font dictionary; if it's inline, make it indirect so it has a stable objnum.
RetainPtr<const CPDF_Object> pFontDict = font->GetFontDict();
if (pFontDict && pFontDict->IsInline()) {
RetainPtr<CPDF_Object> clone = pFontDict->Clone();
document_->AddIndirectObject(clone);
pFontDict = std::move(clone);
}
data.baseFont = font->GetBaseFontName();

// Some (very old/odd) fonts may not expose a dict; fall back safely.
uint32_t font_objnum = pFontDict ? pFontDict->GetObjNum() : 0;

ByteString dict_name;
std::optional<ByteString> maybe_name = obj_holder_->FontsMapSearch(data);
if (maybe_name.has_value()) {
dict_name = std::move(maybe_name.value());
if (font_objnum) {
if (auto hit = obj_holder_->FontsByObjnumSearch(font_objnum)) {
dict_name = *hit;
} else {
// Realize this exact font object into Resources/Font and cache by objnum.
dict_name = RealizeResource(pFontDict.Get(), "Font");
obj_holder_->FontsByObjnumInsert(font_objnum, dict_name);
}
} else {
RetainPtr<const CPDF_Object> pIndirectFont = font->GetFontDict();
if (pIndirectFont->IsInline()) {
// In this case we assume it must be a standard font
// Last-resort path (should be rare): name by (type, base name) like before.
FontData data;
const CPDF_FontEncoding* pEncoding = nullptr;
if (font->IsType1Font()) {
data.type = "Type1";
pEncoding = font->AsType1Font()->GetEncoding();
} else if (font->IsTrueTypeFont()) {
data.type = "TrueType";
pEncoding = font->AsTrueTypeFont()->GetEncoding();
} else if (font->IsCIDFont()) {
data.type = "Type0";
} else {
*buf << "ET"; // bail out cleanly
EndProcessGraphics(*buf);
return;
}
data.baseFont = font->GetBaseFontName();

if (auto hit = obj_holder_->FontsMapSearch(data)) {
dict_name = *hit;
} else {
// Build a minimal indirect font dict (same as your old code).
auto font_dict = pdfium::MakeRetain<CPDF_Dictionary>();
font_dict->SetNewFor<CPDF_Name>("Type", "Font");
font_dict->SetNewFor<CPDF_Name>("Subtype", data.type);
Expand All@@ -990,22 +1179,34 @@ void CPDF_PageContentGenerator::ProcessText(fxcrt::ostringstream* buf,
pEncoding->Realize(document_->GetByteStringPool()));
}
document_->AddIndirectObject(font_dict);
pIndirectFont = std::move(font_dict);
dict_name = RealizeResource(std::move(font_dict), "Font");
obj_holder_->FontsMapInsert(data, dict_name);
}
dict_name = RealizeResource(std::move(pIndirectFont), "Font");
obj_holder_->FontsMapInsert(data, dict_name);
}

pTextObj->SetResourceName(dict_name);

*buf << "/" << PDF_NameEncode(dict_name) << " ";
WriteFloat(*buf, pTextObj->GetFontSize()) << " Tf ";
*buf << static_cast<int>(pTextObj->GetTextRenderMode()) << " Tr ";
ByteString text;
for (uint32_t charcode : pTextObj->GetCharCodes()) {
if (charcode != CPDF_Font::kInvalidCharCode) {
font->AppendChar(&text, charcode);

const float tc = pTextObj->GetCharSpace();
const float tw = pTextObj->GetWordSpace();

if (tc != 0.0f) WriteFloat(*buf, tc) << " Tc ";
if (tw != 0.0f) WriteFloat(*buf, tw) << " Tw ";

if (TextObjectNeedsTJ(pTextObj)) {
WriteTextAsTJ(*buf, pTextObj, font.Get());
*buf << " ET";
} else {
ByteString text;
for (uint32_t charcode : pTextObj->GetCharCodes()) {
if (charcode != CPDF_Font::kInvalidCharCode)
font->AppendChar(&text, charcode);
}
*buf << PDF_HexEncodeString(text.AsStringView()) << " Tj ET";
}
*buf << PDF_HexEncodeString(text.AsStringView()) << " Tj ET";

EndProcessGraphics(*buf);
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions core/fpdfapi/edit/BUILD.gn
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,6 +21,8 @@ source_set("edit") {
"cpdf_pageorganizer.h",
"cpdf_stringarchivestream.cpp",
"cpdf_stringarchivestream.h",
"cpdf_text_redactor.cpp",
"cpdf_text_redactor.h",
]
configs += [
"../../../:pdfium_strict_config",
Expand Down
295 changes: 248 additions & 47 deletions core/fpdfapi/edit/cpdf_pagecontentgenerator.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -30,6 +30,9 @@
#include "core/fpdfapi/page/cpdf_path.h"
#include "core/fpdfapi/page/cpdf_pathobject.h"
#include "core/fpdfapi/page/cpdf_textobject.h"
#include "core/fpdfapi/page/cpdf_color.h"
#include "core/fpdfapi/page/cpdf_colorspace.h"
#include "core/fpdfapi/page/cpdf_iccprofile.h"
#include "core/fpdfapi/parser/cpdf_array.h"
#include "core/fpdfapi/parser/cpdf_dictionary.h"
#include "core/fpdfapi/parser/cpdf_document.h"
Expand All@@ -53,27 +56,56 @@ namespace {
// - ColorSpace
// - Pattern
// - Shading
constexpr const char* kResourceKeys[] = {"ExtGState", "Font", "XObject"};
constexpr const char* kResourceKeys[] = {"ExtGState", "Font", "XObject", "ColorSpace"};

// Key: The resource type.
// Value: The resource names of a given type.
using ResourcesMap = std::map<ByteString, std::set<ByteString>>;

// Returns whether it wrote to `buf` or not.
bool WriteColorToStream(fxcrt::ostringstream& buf, const CPDF_Color* color) {
if (!color || (!color->IsColorSpaceRGB() && !color->IsColorSpaceGray())) {
return false;
bool TextObjectNeedsTJ(const CPDF_TextObject* obj) {
// We don’t have a public accessor for char_codes_, but we can reuse CountItems()
// and GetItemInfo(i). GetItemInfo() gives us char_code_ and (for vert writing)
// origin_. We only need to see if any item has the sentinel.
for (size_t i = 0, n = obj->CountItems(); i < n; ++i) {
auto it = obj->GetItemInfo(i);
if (it.char_code_ == CPDF_Font::kInvalidCharCode)
return true;
}
return false;
}

std::optional<FX_RGB_STRUCT<float>> colors = color->GetRGB();
if (!colors.has_value()) {
return false;
void WriteTextAsTJ(fxcrt::ostringstream& buf,
CPDF_TextObject* obj,
CPDF_Font* font) {
buf << "[ ";
ByteString hexChunk;

for (size_t i = 0, n = obj->CountItems(); i < n; ++i) {
CPDF_TextObject::Item it = obj->GetItemInfo(i);

if (it.char_code_ == CPDF_Font::kInvalidCharCode) {
if (!hexChunk.IsEmpty()) {
buf << PDF_HexEncodeString(hexChunk.AsStringView()) << " ";
hexChunk.clear();
}
float thousandths = 0.0f;
if (obj->GetSeparatorAdjustment(i, &thousandths)) {
// TJ numbers are interpreted as “subtract this from the text position”,
// which matches how CalcPositionDataInternal() used the stored value:
// curpos -= (thousandths * fontSize)/1000. So we emit the value as-is.
WriteFloat(buf, thousandths);
buf << " ";
}
continue;
}

font->AppendChar(&hexChunk, it.char_code_);
}

WriteFloat(buf, colors.value().red) << " ";
WriteFloat(buf, colors.value().green) << " ";
WriteFloat(buf, colors.value().blue);
return true;
if (!hexChunk.IsEmpty()) {
buf << PDF_HexEncodeString(hexChunk.AsStringView()) << " ";
}
buf << "] TJ";
}

// Balances the "q" operator ProcessGraphics() emitted.
Expand DownExpand Up@@ -103,6 +135,11 @@ void RecordPageObjectResourceUsage(const CPDF_PageObject* page_object,
CHECK(!name.IsEmpty());
seen_resources["ExtGState"].insert(name);
}
const CPDF_ColorState& cs = page_object->color_state();
if (!cs.GetFillColorSpaceResName().IsEmpty())
seen_resources["ColorSpace"].insert(cs.GetFillColorSpaceResName());
if (!cs.GetStrokeColorSpaceResName().IsEmpty())
seen_resources["ColorSpace"].insert(cs.GetStrokeColorSpaceResName());
}

CPDF_PageObjectHolder::RemovedResourceMap RemoveUnusedResources(
Expand DownExpand Up@@ -357,6 +394,25 @@ CPDF_PageContentGenerator::GenerateModifiedStreams() {
all_dirty_streams.insert(marked_dirty_streams.begin(),
marked_dirty_streams.end());

// --- embedpdf: if anything is dirty, regenerate *all* page content streams.
// Rationale: CTM / graphics-state handoff between streams means rewriting
// only a subset can leave the concatenated effect inconsistent.
if (!all_dirty_streams.empty()) {
int32_t last_index = -1;
if (RetainPtr<const CPDF_Object> contents =
obj_holder_->GetDict()->GetObjectFor(pdfium::page_object::kContents)) {
if (const CPDF_Array* arr = contents->AsArray()) {
last_index = static_cast<int32_t>(arr->size()) - 1;
} else if (contents->IsStream()) {
last_index = 0;
}
}
for (int32_t i = 0; i <= last_index; ++i) {
all_dirty_streams.insert(i);
}
}
// --- end embedpdf

// Start regenerating dirty streams.
std::map<int32_t, fxcrt::ostringstream> streams;
std::set<int32_t> empty_streams;
Expand DownExpand Up@@ -510,6 +566,109 @@ void CPDF_PageContentGenerator::UpdateResourcesDict() {
obj_holder_->all_removed_resources_map());
}

ByteString CPDF_PageContentGenerator::RealizeColorSpaceObject(
const CPDF_ColorSpace* cs) {
if (!cs) return ByteString();

const auto fam = cs->GetFamily();
if (fam == CPDF_ColorSpace::Family::kDeviceGray ||
fam == CPDF_ColorSpace::Family::kDeviceRGB ||
fam == CPDF_ColorSpace::Family::kDeviceCMYK) {
return ByteString(); // device spaces don't need a resource
}

if (fam == CPDF_ColorSpace::Family::kICCBased) {
RetainPtr<CPDF_IccProfile> profile = cs->GetIccProfile();
if (!profile) return ByteString();

RetainPtr<const CPDF_StreamAcc> acc = profile->GetStreamAcc();
if (!acc)
return ByteString();
RetainPtr<const CPDF_Stream> icc = acc->GetStream();
if (!icc)
return ByteString();

// Stable cache key based on stream objnum
ByteString key = ByteString::Format("ICCB:%u", icc->GetObjNum());
if (auto hit = obj_holder_->ColorSpaceMapSearch(key))
return *hit;

// IMPORTANT: make array indirect
RetainPtr<CPDF_Array> arr = document_->NewIndirect<CPDF_Array>();
arr->AppendNew<CPDF_Name>("ICCBased");
arr->AppendNew<CPDF_Reference>(document_, icc->GetObjNum());

ByteString name = RealizeResource(arr.Get(), "ColorSpace");
obj_holder_->ColorSpaceMapInsert(key, name);
return name;
}

// (CalGray/CalRGB/Lab/Separation/DeviceN can be added later)
return ByteString();
}

bool CPDF_PageContentGenerator::EmitColor(fxcrt::ostringstream& buf,
const CPDF_Color* color,
bool is_stroke,
CPDF_PageObject* owner) {
if (!color) return false;

if (color->IsColorSpaceGray()) {
auto comps = color->GetRawNonPatternComps();
if (comps.size() == 1) {
WriteFloat(buf, comps[0]) << (is_stroke ? " G " : " g ");
// device space → clear any remembered resource name
if (is_stroke) owner->mutable_color_state().SetStrokeColorSpaceResName({});
else owner->mutable_color_state().SetFillColorSpaceResName({});
return true;
}
return false;
}

if (color->IsColorSpaceRGB()) {
auto rgb = color->GetRGB();
if (!rgb) return false;
WriteFloat(buf, rgb->red) << " ";
WriteFloat(buf, rgb->green) << " ";
WriteFloat(buf, rgb->blue) << (is_stroke ? " RG " : " rg ");
if (is_stroke) owner->mutable_color_state().SetStrokeColorSpaceResName({});
else owner->mutable_color_state().SetFillColorSpaceResName({});
return true;
}

if (color->IsColorSpaceCMYK()) {
auto comps = color->GetRawNonPatternComps(); // expect 4
if (comps.size() == 4) {
WriteFloat(buf, comps[0]) << " ";
WriteFloat(buf, comps[1]) << " ";
WriteFloat(buf, comps[2]) << " ";
WriteFloat(buf, comps[3]) << (is_stroke ? " K " : " k ");
if (is_stroke) owner->mutable_color_state().SetStrokeColorSpaceResName({});
else owner->mutable_color_state().SetFillColorSpaceResName({});
return true;
}
return false;
}

// Non-device: realize resource + scn/SCN
const CPDF_ColorSpace* cs = color->GetColorSpace();
ByteString cs_name = RealizeColorSpaceObject(cs);
if (cs_name.IsEmpty()) return false;

if (is_stroke) owner->mutable_color_state().SetStrokeColorSpaceResName(cs_name);
else owner->mutable_color_state().SetFillColorSpaceResName(cs_name);

buf << "/" << PDF_NameEncode(cs_name) << (is_stroke ? " CS " : " cs ");

auto comps = color->GetRawNonPatternComps();
for (size_t i = 0; i < comps.size(); ++i) {
if (i) buf << " ";
WriteFloat(buf, comps[i]);
}
buf << (is_stroke ? " SCN " : " scn ");
return true;
}

ByteString CPDF_PageContentGenerator::RealizeResource(
const CPDF_Object* pResource,
ByteStringView type) const {
Expand DownExpand Up@@ -819,11 +978,11 @@ void CPDF_PageContentGenerator::ProcessPath(fxcrt::ostringstream* buf,
void CPDF_PageContentGenerator::ProcessGraphics(fxcrt::ostringstream* buf,
CPDF_PageObject* pPageObj) {
*buf << "q ";
if (WriteColorToStream(*buf, pPageObj->color_state().GetFillColor())) {
*buf << " rg ";
if (const CPDF_Color* fill = pPageObj->color_state().GetFillColor()) {
EmitColor(*buf, fill, /*is_stroke=*/false, pPageObj);
}
if (WriteColorToStream(*buf, pPageObj->color_state().GetStrokeColor())) {
*buf << " RG ";
if (const CPDF_Color* stroke = pPageObj->color_state().GetStrokeColor()) {
EmitColor(*buf, stroke, /*is_stroke=*/true, pPageObj);
}
float line_width = pPageObj->graph_state().GetLineWidth();
if (line_width != 1.0f) {
Expand DownExpand Up@@ -909,7 +1068,7 @@ void CPDF_PageContentGenerator::ProcessGraphics(fxcrt::ostringstream* buf,

void CPDF_PageContentGenerator::ProcessDefaultGraphics(
fxcrt::ostringstream* buf) {
*buf << "0 0 0 RG 0 0 0 rg 1 w "
*buf << "1 w "
<< static_cast<int>(CFX_GraphStateData::LineCap::kButt) << " J "
<< static_cast<int>(CFX_GraphStateData::LineJoin::kMiter) << " j\n";
default_graphics_name_ = GetOrCreateDefaultGraphics();
Expand DownExpand Up@@ -948,39 +1107,69 @@ void CPDF_PageContentGenerator::ProcessText(fxcrt::ostringstream* buf,
ProcessGraphics(buf, pTextObj);
*buf << "BT ";

const CFX_Matrix& matrix = pTextObj->GetTextMatrix();
if (!matrix.IsIdentity()) {
WriteMatrix(*buf, matrix) << " Tm ";
// Separate translation (cm) from pure text matrix (Tm)
const CFX_Matrix& M = pTextObj->GetTextMatrix();
if (M.e != 0 || M.f != 0) {
WriteMatrix(*buf, CFX_Matrix(1, 0, 0, 1, M.e, M.f)) << " cm ";
}

CFX_Matrix TmNoTranslate(M.a, M.b, M.c, M.d, 0, 0);
if (!TmNoTranslate.IsIdentity()) {
WriteMatrix(*buf, TmNoTranslate) << " Tm ";
} else {
*buf << "1 0 0 1 0 0 Tm ";
}

// Ensure we have a font.
RetainPtr<CPDF_Font> font(pTextObj->GetFont());
if (!font) {
font = CPDF_Font::GetStockFont(document_, "Helvetica");
}

FontData data;
const CPDF_FontEncoding* pEncoding = nullptr;
if (font->IsType1Font()) {
data.type = "Type1";
pEncoding = font->AsType1Font()->GetEncoding();
} else if (font->IsTrueTypeFont()) {
data.type = "TrueType";
pEncoding = font->AsTrueTypeFont()->GetEncoding();
} else if (font->IsCIDFont()) {
data.type = "Type0";
} else {
return;
// --- Object-number keyed font resource binding ---
// Get the font dictionary; if it's inline, make it indirect so it has a stable objnum.
RetainPtr<const CPDF_Object> pFontDict = font->GetFontDict();
if (pFontDict && pFontDict->IsInline()) {
RetainPtr<CPDF_Object> clone = pFontDict->Clone();
document_->AddIndirectObject(clone);
pFontDict = std::move(clone);
}
data.baseFont = font->GetBaseFontName();

// Some (very old/odd) fonts may not expose a dict; fall back safely.
uint32_t font_objnum = pFontDict ? pFontDict->GetObjNum() : 0;

ByteString dict_name;
std::optional<ByteString> maybe_name = obj_holder_->FontsMapSearch(data);
if (maybe_name.has_value()) {
dict_name = std::move(maybe_name.value());
if (font_objnum) {
if (auto hit = obj_holder_->FontsByObjnumSearch(font_objnum)) {
dict_name = *hit;
} else {
// Realize this exact font object into Resources/Font and cache by objnum.
dict_name = RealizeResource(pFontDict.Get(), "Font");
obj_holder_->FontsByObjnumInsert(font_objnum, dict_name);
}
} else {
RetainPtr<const CPDF_Object> pIndirectFont = font->GetFontDict();
if (pIndirectFont->IsInline()) {
// In this case we assume it must be a standard font
// Last-resort path (should be rare): name by (type, base name) like before.
FontData data;
const CPDF_FontEncoding* pEncoding = nullptr;
if (font->IsType1Font()) {
data.type = "Type1";
pEncoding = font->AsType1Font()->GetEncoding();
} else if (font->IsTrueTypeFont()) {
data.type = "TrueType";
pEncoding = font->AsTrueTypeFont()->GetEncoding();
} else if (font->IsCIDFont()) {
data.type = "Type0";
} else {
*buf << "ET"; // bail out cleanly
EndProcessGraphics(*buf);
return;
}
data.baseFont = font->GetBaseFontName();

if (auto hit = obj_holder_->FontsMapSearch(data)) {
dict_name = *hit;
} else {
// Build a minimal indirect font dict (same as your old code).
auto font_dict = pdfium::MakeRetain<CPDF_Dictionary>();
font_dict->SetNewFor<CPDF_Name>("Type", "Font");
font_dict->SetNewFor<CPDF_Name>("Subtype", data.type);
Expand All@@ -990,22 +1179,34 @@ void CPDF_PageContentGenerator::ProcessText(fxcrt::ostringstream* buf,
pEncoding->Realize(document_->GetByteStringPool()));
}
document_->AddIndirectObject(font_dict);
pIndirectFont = std::move(font_dict);
dict_name = RealizeResource(std::move(font_dict), "Font");
obj_holder_->FontsMapInsert(data, dict_name);
}
dict_name = RealizeResource(std::move(pIndirectFont), "Font");
obj_holder_->FontsMapInsert(data, dict_name);
}

pTextObj->SetResourceName(dict_name);

*buf << "/" << PDF_NameEncode(dict_name) << " ";
WriteFloat(*buf, pTextObj->GetFontSize()) << " Tf ";
*buf << static_cast<int>(pTextObj->GetTextRenderMode()) << " Tr ";
ByteString text;
for (uint32_t charcode : pTextObj->GetCharCodes()) {
if (charcode != CPDF_Font::kInvalidCharCode) {
font->AppendChar(&text, charcode);

const float tc = pTextObj->GetCharSpace();
const float tw = pTextObj->GetWordSpace();

if (tc != 0.0f) WriteFloat(*buf, tc) << " Tc ";
if (tw != 0.0f) WriteFloat(*buf, tw) << " Tw ";

if (TextObjectNeedsTJ(pTextObj)) {
WriteTextAsTJ(*buf, pTextObj, font.Get());
*buf << " ET";
} else {
ByteString text;
for (uint32_t charcode : pTextObj->GetCharCodes()) {
if (charcode != CPDF_Font::kInvalidCharCode)
font->AppendChar(&text, charcode);
}
*buf << PDF_HexEncodeString(text.AsStringView()) << " Tj ET";
}
*buf << PDF_HexEncodeString(text.AsStringView()) << " Tj ET";

EndProcessGraphics(*buf);
}
Loading