//
// This code is part of Document Solutions for PDF demos.
// Copyright (c) MESCIUS inc. All rights reserved.
//
using System;
using System.IO;
using System.Drawing;
using GrapeCity.Documents.Pdf;
using GrapeCity.Documents.Pdf.TextMap;
using GrapeCity.Documents.Pdf.Text;
using GrapeCity.Documents.Text;
using GrapeCity.Documents.Pdf.Spec;
using System.Collections.Immutable;
using System.Collections.Generic;
using System.Linq;
namespace DsPdfWeb.Demos
{
// This sample loads an existing PDF, enumerates the fonts used in it,
// determines whether each font is embedded, and prints the list of fonts
// along with their embedding status on the first page of the resulting PDF,
// followed by the original document.
//
// Note: The check for whether a font is embedded is reliable.
// However, determining whether an embedded font is a full font or a subset
// is heuristic and may not be accurate for all PDFs.
public class FontEmbeddingStatus
{
public int CreatePDF(Stream stream)
{
// This function checks whether a font is embedded, and if it is,
// also tries to determine whether it is a subset or a complete font.
// For embedded subsets, the name usually contains a prefix ending with '+'
// which we strip from the name for display (as does Acrobat).
(FontEmbedMode, string) GetFontInfo(GrapeCity.Documents.Pdf.Text.Font font)
{
if (font.IsEmbedded)
{
int p = font.BaseFont.IndexOf('+');
if (p > 0)
return (FontEmbedMode.EmbedSubset, font.BaseFont[(p + 1)..]);
else
return (FontEmbedMode.EmbedFullFont, font.BaseFont);
}
return (FontEmbedMode.NotEmbed, font.BaseFont);
}
string EmbedModeToString(FontEmbedMode fem)
{
if (fem == FontEmbedMode.EmbedFullFont)
return "Embedded font";
else if (fem == FontEmbedMode.EmbedSubset)
return "Embedded subset";
else
return "Not embedded";
}
const string pdfName = "C1Olap-QuickStart.pdf";
var fs = File.OpenRead(Path.Combine("Resources", "PDFs", pdfName));
var doc = new GcPdfDocument();
doc.Load(fs);
var page = doc.Pages.Insert(0);
var g = page.Graphics;
var tl = g.CreateTextLayout();
tl.AppendLine($"Fonts used in {pdfName}, and their embedding status:\n");
// List fonts and their embedding states:
var ff = doc.GetFonts().ToImmutableArray().Select(f_ => GetFontInfo(f_)).DistinctBy(fi_ => fi_.Item2).OrderBy(fi_ => fi_.Item2);
foreach (var fi in ff)
tl.AppendLine($"- \"{fi.Item2}\": {EmbedModeToString(fi.Item1)}");
tl.MarginAll = g.Resolution;
g.DrawTextLayout(tl, Point.Empty);
doc.Save(stream);
return doc.Pages.Count;
}
}
}