I need to loop through the elements of a existing (base) PDF (it’s a certificate) and change the Fill color of certain PDF Path elements but I also notice that paths can be in a PdfGroupContent element as well.
Q1: What is the best way to find all ‘Paths’ in the document or do I just need to write code to loop through all document elements to find them?
Q2: The best way I can think of indicating which ‘Paths’ need to have their color changed, is to set them to a unusual color in the base PDF, then if the element has that color, change it. Am I missing a simpler way to achieve this solution?
using var document = PdfDocument.Load("input.pdf");
var page = document.Pages[0];
foreach (var pathElement in page.Content.Elements.All(true).OfType<PdfPathContent>())
{
// ...
}
A2: Are the targeted path elements in a specific area?
If you are, you could try using this:
using var document = PdfDocument.Load(desktop + "\\input.pdf");
var page = document.Pages[0];
double areaLeft = 100,
areaRight = 200,
areaBottom = 300,
areaTop = 400;
var contentEnumerator = page.Content.Elements.All(page.Transform, true).GetEnumerator();
while (contentEnumerator.MoveNext())
{
if (contentEnumerator.Current.ElementType != PdfContentElementType.Path)
continue;
var pathElement = (PdfPathContent)contentEnumerator.Current;
var bounds = pathElement.Bounds;
contentEnumerator.Transform.Transform(ref bounds);
if (bounds.Left > areaLeft && bounds.Right < areaRight && bounds.Bottom > areaBottom && bounds.Top < areaTop)
{
// ...
}
}
Dim borderColour As GemBox.Pdf.Content.PdfColor = GemBox.Pdf.Content.PdfColor.FromRgb(borderR1 / 255, borderG1 / 255, borderB1 / 255)
Dim contentEnumerator = page1.Content.Elements.All(page1.Transform).GetEnumerator()
While contentEnumerator.MoveNext()
Select contentEnumerator.Current.ElementType
Case GemBox.Pdf.Content.PdfContentElementType.Path
process_gemboxPath(contentEnumerator.Current, borderColour)
Case GemBox.Pdf.Content.PdfContentElementType.Group
process_gemboxGroup(contentEnumerator.Current, borderColour)
End Select
End While
Private Sub process_gemboxGroup(ByRef g1 As GemBox.Pdf.Content.PdfContentGroup, borderColour As GemBox.Pdf.Content.PdfColor)
For Each e3 In g1.Elements
Select Case e3.ElementType
Case GemBox.Pdf.Content.PdfContentElementType.Path
process_gemboxPath(e3, borderColour)
Case GemBox.Pdf.Content.PdfContentElementType.Group
process_gemboxGroup(e3, borderColour)
End Select
Next
End Sub
Private Sub process_gemboxPath(ByRef p1 As GemBox.Pdf.Content.PdfPathContent, borderColour As GemBox.Pdf.Content.PdfColor)
p1.Format.Fill.Color = borderColour
End Sub
While creating your last request, I realized that I had to change the color of both Fill and Stroke to get all objects to be of the same color. Obvious when I think about it now!
Anyway, thank you for your help and code to my original question.