Giter Site home page Giter Site logo

ststeiger / pdfsharpcore Goto Github PK

View Code? Open in Web Editor NEW
1.0K 36.0 224.0 2.13 MB

Port of the PdfSharp library to .NET Core - largely removed GDI+ (only missing GetFontData - which can be replaced with freetype2)

License: Other

C# 96.04% Batchfile 0.01% Smalltalk 3.95% PowerShell 0.01%
pdfsharp xamarin imagesharp pdf csharp netcore2 netstandard20 alpha

pdfsharpcore's Introduction

PdfSharpCore

NuGet Version CI codecov.io

PdfSharpCore is a partial port of PdfSharp.Xamarin for .NET Standard. Additionally MigraDoc has been ported as well (from version 1.32). Image support has been implemented with SixLabors.ImageSharp and Fonts support with SixLabors.Fonts.

Table of Contents

Example

The following code snippet creates a simple PDF-file with the text 'Hello World!'. The code is written for a .NET 6 console app with top level statements.

using PdfSharpCore.Drawing;
using PdfSharpCore.Fonts;
using PdfSharpCore.Pdf;
using PdfSharpCore.Utils;

GlobalFontSettings.FontResolver = new FontResolver();

var document = new PdfDocument();
var page = document.AddPage();

var gfx = XGraphics.FromPdfPage(page);
var font = new XFont("Arial", 20, XFontStyle.Bold);

var textColor = XBrushes.Black;
var layout = new XRect(20, 20, page.Width, page.Height);
var format = XStringFormats.Center;

gfx.DrawString("Hello World!", font, textColor, layout, format);

document.Save("helloworld.pdf");

Contributing

We appreciate feedback and contribution to this repo!

License

This software is released under the MIT License. See the LICENSE file for more info.

PdfSharpCore relies on the following projects, that are not under the MIT license:

  • SixLabors.ImageSharp and SixLabors.Fonts

pdfsharpcore's People

Contributors

artehe avatar ascott18 avatar ashishjagdale84 avatar baskren avatar devbar avatar foobar2016 avatar jafin avatar jeffreycoxdoosan avatar jetski5822 avatar marv51 avatar methuselah96 avatar michelmichels avatar mishun avatar mitchcapper avatar nils-a avatar noctis0430 avatar officedevunofficial avatar packdat avatar parknert avatar rendermichael avatar saikatguha avatar sanglanun avatar sappharad avatar schtho avatar schtritoff avatar startnow65 avatar steeltomato avatar ststeiger avatar thhhza avatar tinokrueger avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pdfsharpcore's Issues

MigraDocCore.DocumentObjectModel.Document does not exist in the namespace MigraDocCore.DocumentObjectModel

First, thanks for sharing this project!

I'm using your nuget package. I'm trying to use MigraDocCore's Document object for it's table features, but I'm getting an error "MigraDocCore.DocumentObjectModel.Document does not exist in the namespace MigraDocCore.DocumentObjectModel."

The Document class is implemented in this project here:
https://github.com/ststeiger/PdfSharpCore/blob/master/MigraDocCore.DocumentObjectModel/MigraDoc/MigraDoc.DocumentObjectModel/Document.cs

In fact the only MigraDocCore class I'm able to access is: MigraDocCore.DocumentObjectModel.MigraDoc.DocumentObjectModel.Shapes.ImageSource
Note the funky namespace path. Maybe that gives us a hint?

Cheers!

Edit: I believe the current nuget package does not contain the MigraDocCore.DocumentObjectModel DLL file. I was thrown off by MigraDocCore.DocumentObjectModel.MigraDoc.DocumentObjectModel.Shapes.ImageSource being accessible.

Create new page issue

Hi,
I'm using PdfSharpCore in Xamarin Forms 3.0 project and I'm getting error called Neutral region info when I'm trying to create new PdfPage. It's not happening always.

Code where exception is thrown
PdfPage page = new PdfPage();

Here is exception details.
{System.NotImplementedException: Neutral region info
at System.Globalization.RegionInfo..ctor (System.Globalization.CultureInfo ci) [0x00083] in :0
at System.Globalization.RegionInfo.get_CurrentRegion () [0x00012] in :0
at PdfSharpCore.Pdf.PdfPage.Initialize () [0x00000] in :0
at PdfSharpCore.Pdf.PdfPage..ctor () [0x00026] in :0
at GTS.Mobile.PDF.PdfSharpCore.PdfSharpCoreGenerator.AddPage (System.Double height) [0x00001] in C:\Projects\Servitrax\Source\GTS.Mobile\GTS.Mobile\GTS.Mobile\PDF\PdfSharpCore\PdfSharpCoreGenerator.cs:91
at GTS.Mobile.PDF.PdfSharpCore.PdfSharpCoreGenerator..ctor (GTS.Mobile.Data.Delivery.IPDTFileDataService pDTFileDataService, System.Double height) [0x0002e] in C:\Projects\Servitrax\Source\GTS.Mobile\GTS.Mobile\GTS.Mobile\PDF\PdfSharpCore\PdfSharpCoreGenerator.cs:45
at GTS.Mobile.PDF.Report.DeliveryOrderReportPDF+d__17.MoveNext () [0x003d4] in C:\Projects\Servitrax\Source\GTS.Mobile\GTS.Mobile\GTS.Mobile\PDF\Report\DeliveryOrderReportPDF.cs:107 }

" at System.Globalization.RegionInfo..ctor (System.Globalization.CultureInfo ci) [0x00083] in <d4a23…"

Object already in table

Could we please adjust the following so it logs a warning rather than throws an exception when there are duplicates in the PDF. I have a PDF that will read in chrome, edge, adobe, and used to work in the .net framework iTextSharp version but it will not work with PdfSharpCore. I understand it is technically an invalid PDF but the standard appears to be to ignore subsequent duplicates and keep the first encountered.

throw new InvalidOperationException("Object already in table.");

IntersectClip not applied to text

Using PdfSharp XGraphics.IntersectClip affects subsequently rendered text. However in PdfSharpCore, the text is not clipped to the rectangle.

The following code produces clipped output using PdfSharp (in a .NET Framework project) but unclipped output using PdfSharpCore (in a .NET Core project).

    static void Main(string[] args)
    {
        using (PdfDocument doc = new PdfDocument())
        {
            PdfPage page = doc.AddPage();

            using (XGraphics g = XGraphics.FromPdfPage(page))
            {
                XRect clip = new XRect(50.0, 50.0, 70.0, 70.0);
                g.IntersectClip(clip);

                XFont font = new XFont("Times New Roman", 28.0);
                g.DrawString("Here is Text!", font, new XSolidBrush(XColor.FromKnownColor(XKnownColor.Black)), new XPoint(100.0, 100.0));
            }

            doc.Save(@"c:\pete\pdfsharp.pdf");
        }
    }

PDF to Image (getting a thumbnail)

Hi!

I know that thumbnail support is not even part of PDFSharp, but, it is feasible to implement it on PDFSharpCore? Would be very useful to get a thumbnail of a given PDFPage.

Not sure how complex this can be, but I think there's no need for a production ready PDF-to-image renderer (just small resolution thumbnails).
I don't want to rely on ghostscript or other native libraries, this should be really cross-platform!

Throughts?

Thank you!

InvalidCastException upon Open

Hi there. I am trying to get the pdf parsing working in a .NET Core application, but receive this exception immediately upon trying to open the pdf:

exception	{System.InvalidCastException: Unable to cast object of type 'PdfSharpCore.Pdf.PdfInteger' to type 'System.IConvertible'.
   at System.Convert.ToInt32(Object value)
   at PdfSharpCore.Pdf.IO.Parser.GetStreamLength(PdfDictionary dict)
   at PdfSharpCore.Pdf.IO.Parser.ReadObject(PdfObject pdfObject, PdfObjectID objectID, Boolean includeReferences, Boolean fromObjecStream)
   at PdfSharpCore.Pdf.IO.PdfReader.Open(Stream stream, String password, PdfDocumentOpenMode openmode, PdfPasswordProvider passwordProvider)
   at PdfSharpCore.Pdf.IO.PdfReader.Open(Stream stream, String password, PdfDocumentOpenMode openmode)
   at PdfSharpCore.Pdf.IO.PdfReader.Open(Stream stream, PdfDocumentOpenMode openmode)

The code is simply this at the moment:

            Stream stream = File.OpenRead(path);
            PdfDocument book = PdfReader.Open(stream, PdfDocumentOpenMode.ReadOnly);
            Console.WriteLine(string.Format("\tPageCount = {0}", book.PageCount));

where it fails on the second one. Any suggestions on how to fix the issue?

I have tested with this pdf (placed in local filesystem)

Unable to build UWP release version

Version Visual Studio 16.2.3
UWP target: 17763

I have done a project in Xamarin that includes its plugin, in Debug mode it works perfectly, but when I try to make the output in release mode I get the following error:

Error ILT0005: 'C:\Program Files (x86)\Microsoft SDKs\UWPNuGetPackages\runtime.win10-x86.microsoft.net.native.compiler\2.2.3\tools\x86\ilc\Tools\nutc_driver.exe @"C:\Users\Ivan Labradorr\source\repos\CinarucoProject\cinarucoproject\Cinaruco\Cinaruco.UWP\obj\x86\Release\ilc\intermediate\MDIL\Cinaruco.UWP.rsp"' returned exit code 1 Cinaruco.UWP

Error: NUTC3033:Internal Compiler Error: Invalid MethodImpl body=6000353 decl=600032d when loading type 'SixLabors.ImageSharp.Processing.Processors.Quantization.PaletteQuantizer1<TPixel>' from assembly 'SixLabors.ImageSharp' while loading MethodImpl list for 'instance SixLabors.ImageSharp.Processing.Processors.Quantization.IFrameQuantizer1 SixLabors.ImageSharp.Processing.Processors.Quantization.PaletteQuantizer1<TPixel>.SixLabors.ImageSharp.Processing.Processors.Quantization.IQuantizer.CreateFrameQuantizer<TPixel1>(SixLabors.ImageSharp.Configuration)'. while loading type 'SixLabors.ImageSharp.Processing.Processors.Quantization.PaletteQuantizer1'. while computing compilation roots. Cinaruco.UWP

Type 'ZXing.Rendering.PixelData' from assembly 'ZXing' was not included in compilation, but was referenced in method 'bi.b(List, IBuffer, QrCodeModel, QrCodeLevel, int, int)'. There may have been a missing assembly, or a dependency on a more recent Windows SDK release. Cinaruco.UWP

PDF Generated with Wingings Font

When I generate a pdf and upload it to azure blob storage, the html string I'm passing in is somehow being turned into Wingdings when I generate the PDF.

var html = "<p>Normal HTML Content</p>";

// Create CarrierHQ pdf from HTML
var pdf = VetCV.HtmlRendererCore.PdfSharpCore.PdfGenerator.GeneratePdf(html, PageSize.A4);
            
//  ** Removing this doesn't help **
// Download and append Aon pdf to CarrierHQ pdf
var appendBlob = container.GetBlockBlobReference("append.pdf");
await using (var ms = new MemoryStream())
{ 
    await appendBlob.DownloadToStreamAsync(ms);
    var appendPdf = PdfReader.Open(ms, PdfDocumentOpenMode.Import);
    foreach (PdfPage page in appendPdf.Pages)
    { 
         pdf.AddPage(page);
    }
}

 // Upload final document to Azure
using (var ms = new MemoryStream())
{ 
      pdf.Save(ms);
      await chqBlob.UploadFromStreamAsync(ms);
}

The weirdest part is when I copy-paste the wingdings text into Word, it pastes in English.....

Debug version was shipped on NuGet, crashing apps on Debug.Assert

The version distributed on NuGet was built in Debug configuration and crashes apps on Debug.Assert() statements (in our case inside PdfString).
This is super bad because it will use Environment.FailFast() when run in production, crashing the app without an option to recover. Even more unhelpful: the asp.net core IIS module doesn't restart the app in this case and continues to send 502 responses until the app pool is recycled. (which isn't your problem, but this is how we were alerted to the problem)

Image cannot be loaded. Available decoders: - BMP : BmpDecoder - PNG : PngDecoder - JPEG : JpegDecoder - GIF : GifDecoder

I was using PdfSharp, after upgrading to PdfSharpCore an error occurred to load the image in DrawImage.

It was PdfSharp this way and worked: XImage image = XImage.FromStream (Stream);
graphics.DrawImage (image, 5, 5, 586, 815);

After migrating to PdfSharpCore, the error started
Image can not be loaded. Available decoders: - BMP: BmpDecoder - PNG: PngDecoder - JPEG: JpegDecoder - GIF: GifDecoder

As I'm using now: XImage image = XImage.FromStream (() => Stream);
graphics.DrawImage (image, 5, 5, 586, 815);

the error happens here: graphics.DrawImage (image, 5, 5, 586, 815);
I've tried it anyway, does anyone know any formula to fix this?
Thank you.

Transparent Image is rendering with a black background

I am trying to embed a image with transparent background to a PDF using PDFSharp (for .NET Core). The image is rendering with a black background.

My guess is on Windows the transparent background is handled by GDIPlus.dll which might not be available on Linux. Do we have a workaround for it?

Problem with opening the document

Hi, I am trying to use PdfSharpCore in project .NetCoreApp,Version=v1.1.
"Microsoft.NETCore.App": {
"version": "1.1.4",
"type": "platform"
},

But I have the problem with opening PDF.

This is the code:
PdfDocument doc = PdfReader.Open(path);
After openning the doc is null and I had no exception.

Please, describe what have do to open pdfdocument correct?

Input string was not in a correct format

in Pdf.IO\Lexer.cs, line 568 (probably applies to 567 as well), if _nextChar == ' ' (empty space) for whatever reason, Input string was not in a correct format error is thrown.

MissingMethodException: Method not found: 'Void SixLabors.ImageSharp.ImageExtensions.SaveAsJpeg

Hi

I'm facing a problem with jpg images:

....
XImage image = XImage.FromFile(logo);
double x = (250 - image.PixelWidth * 72 / image.HorizontalResolution) / 2;
gfx.DrawImage(image, x, 0);
....

Exception:

MissingMethodException: Method not found: 'Void SixLabors.ImageSharp.ImageExtensions.SaveAsJpeg(SixLabors.ImageSharp.Image`1<!!0>, System.IO.Stream, SixLabors.ImageSharp.Formats.Jpeg.JpegEncoder)'.

The same lines shown above are working fine with png images

PdfSharpCore Version="1.1.18"
SixLabors.ImageSharp Version="1.0.0-beta0007"
Linux

Conversion from HTML to PDF

I want to convert html to pdf. How to acheive it with this library.
PdfGenerator class from PdfSharp seems to be missing.

Add security password to PDF

Hi, I'm follow this sample to add password security into the PDF generated. But there is an error here.
1

Below is my code for adding security:
PdfSecuritySettings securitySettings = document.SecuritySettings;
securitySettings.UserPassword = "user";
securitySettings.OwnerPassword = "owner";

I already checking PDFSharp forum, but didn't found any error regarding this. Can you help me?

Draw a PNG image with transparency

Hi,
first thanks for port this to .NET Standard
I'm having problems reading a pdf file and trying to draw a png image loaded from a file
this is my code

using System.IO;
using PdfSharpCore.Drawing;
using PdfSharpCore.Pdf;
using PdfSharpCore.Pdf.IO;

namespace PdfTest
{
    class Program
    {
        static void Main(string[] args)
        {
            if (File.Exists("edited.pdf"))
                File.Delete("edited.pdf");

            PdfDocument document = PdfReader.Open("original.pdf", PdfDocumentOpenMode.Modify);
            var page = document.Pages[0];
            var gfx = XGraphics.FromPdfPage(page);
            // var image = XImage.FromFile("Firma2.jpg");
            var image = XImage.FromFile("Firma.png");
            double width = image.PixelWidth * 4.5 / image.HorizontalResolution;
            double height = image.PixelHeight * 4.5 / image.HorizontalResolution;
            gfx.DrawImage(image, 51, page.Height - 140, width, height);
            document.Save("edited.pdf");
        }
    }
}

When I use the Nuget Package PdfSharpCore v1.1.8 a black rectangle is drawn
image
I downgraded versions and it occur in all of them

When I use a jpg file, it is drawn ok, but jpg has no transparency and I need that

I reproduce the same piece of code with the same data using the original Nuget Package PDFsharp v1.50.5147 (using .NetFramework v4.7) and it is drawn correctly

Here is the data I am using for tests:
edited.pdf
Firma.png
Firma2.jpg
original.pdf

The text "∅" cannot show the problem

Use the "simsun.ttf" font,
In pdfsharp, "∅22" will display "∅22"
In pdfsharpCore, “∅22” will display “22” and “∅” will not be displayed.

MissingManifestResourceException at read pdf.

When read a pdf, I found this Exception occure.

PdfSharpCore.Pdf.IO.PdfReaderException: UNEXPECTED ERROR while formatting message with ID UnexpectedToken: System.Resources.MissingManifestResourceException: Could not find any resources appropriate for the specified culture or the neutral culture.  Make sure "PdfSharpCore.Resources.Messages.resources" was correctly embedded or linked into assembly "PdfSharpCore" at compile time, or that all the satellite assemblies required are loadable and fully signed.
   at System.Resources.ManifestBasedResourceGroveler.HandleResourceStreamMissing(String fileName)
   at System.Resources.ManifestBasedResourceGroveler.GrovelForResourceSet(CultureInfo culture, Dictionary`2 localResourceSets, Boolean tryParents, Boolean createIfNotExists, StackCrawlMark& stackMark)
   at System.Resources.ResourceManager.InternalGetResourceSet(CultureInfo requestedCulture, Boolean createIfNotExists, Boolean tryParents, StackCrawlMark& stackMark)
   at System.Resources.ResourceManager.InternalGetResourceSet(CultureInfo culture, Boolean createIfNotExists, Boolean tryParents)
   at System.Resources.ResourceManager.GetString(String name, CultureInfo culture)
   at PdfSharpCore.PSSR.GetString(PSMsgID id)
   at PdfSharpCore.PSSR.Format(PSMsgID id, Object[] args)
   at PdfSharpCore.Internal.ParserDiagnostics.ThrowParserException(String message)
   at PdfSharpCore.Pdf.IO.Parser.ReadObject(PdfObject pdfObject, PdfObjectID objectID, Boolean includeReferences, Boolean fromObjecStream)
   at PdfSharpCore.Pdf.IO.PdfReader.Open(Stream stream, String password, PdfDocumentOpenMode openmode, PdfPasswordProvider passwordProvider)
{$... and my codes}

and I not found PdfSharpCore/Resources/Messages.resources in this repository.
Is this correct?

Only supports .NETCoreApp, rather than .NETStandard

The first line of the description states:

PdfSharpCore is a partial port of PdfSharp.Xamarin for .NET Standard

This is misleading, as it simply targets .NETCoreApp, which means I won't be able to include this in a .NETStandard library.

image

PdfSharpCore w/ Azure

Attempting to use this library with an asp.net core application hosted in Azure. The library is expecting Windows to be located on C:/ but for Azure App Services its located on the D:/. I believe the issue is in PdfSharpCore.Utils.FontResolver's static FontResolver and the fix would be to change @"C:\Windows\Fonts" to Environment.ExpandEnvironmentVariables(@"%SystemRoot%\Fonts") it would fix my issue

Encoding 1252 error in .net core project

I am getting the following error in my stacktrace. Please help me in resolving the above issue.

Unhandled exception. System.NotSupportedException: No data is available for encoding 1252. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method. at System.Text.Encoding.GetEncoding(Int32 codepage) at PdfSharp.Pdf.Internal.PdfEncoders.get_WinAnsiEncoding() at PdfSharp.Fonts.OpenType.OpenTypeDescriptor.Initialize() at PdfSharp.Fonts.OpenType.OpenTypeDescriptor..ctor(String fontDescriptorKey, XFont font) at PdfSharp.Fonts.FontDescriptorCache.GetOrCreateDescriptorFor(XFont font) at PdfSharp.Drawing.XFont.CreateDescriptorAndInitializeFontMetrics() at PdfSharp.Drawing.XFont.Initialize() at PdfSharp.Drawing.XFont..ctor(String familyName, Double emSize, XFontStyle style, XPdfFontOptions pdfOptions) at MigraDoc.Rendering.FontHandler.FontToXFont(Font font, PdfFontEncoding encoding) at MigraDoc.Rendering.ParagraphRenderer.get_CurrentFont() at MigraDoc.Rendering.ParagraphRenderer.CalcCurrentVerticalInfo() at MigraDoc.Rendering.ParagraphRenderer.InitFormat(Area area, FormatInfo previousFormatInfo) at MigraDoc.Rendering.ParagraphRenderer.Format(Area area, FormatInfo previousFormatInfo) at MigraDoc.Rendering.TopDownFormatter.FormatOnAreas(XGraphics gfx, Boolean topLevel) at MigraDoc.Rendering.FormattedCell.Format(XGraphics gfx) at MigraDoc.Rendering.TableRenderer.FormatCells() at MigraDoc.Rendering.TableRenderer.InitFormat(Area area, FormatInfo previousFormatInfo) at MigraDoc.Rendering.TableRenderer.Format(Area area, FormatInfo previousFormatInfo) at MigraDoc.Rendering.TopDownFormatter.FormatOnAreas(XGraphics gfx, Boolean topLevel) at MigraDoc.Rendering.FormattedTextFrame.Format(XGraphics gfx) at MigraDoc.Rendering.TextFrameRenderer.Format(Area area, FormatInfo previousFormatInfo) at MigraDoc.Rendering.TopDownFormatter.FormatOnAreas(XGraphics gfx, Boolean topLevel) at MigraDoc.Rendering.FormattedCell.Format(XGraphics gfx) at MigraDoc.Rendering.TableRenderer.FormatCells() at MigraDoc.Rendering.TableRenderer.InitFormat(Area area, FormatInfo previousFormatInfo) at MigraDoc.Rendering.TableRenderer.Format(Area area, FormatInfo previousFormatInfo) at MigraDoc.Rendering.TopDownFormatter.FormatOnAreas(XGraphics gfx, Boolean topLevel) at MigraDoc.Rendering.FormattedHeaderFooter.Format(XGraphics gfx) at MigraDoc.Rendering.FormattedDocument.FormatHeader(HeaderFooterPosition hfp, HeaderFooter header) at MigraDoc.Rendering.FormattedDocument.FormatHeadersFooters() at MigraDoc.Rendering.FormattedDocument.MigraDoc.Rendering.IAreaProvider.GetNextArea() at MigraDoc.Rendering.TopDownFormatter.FormatOnAreas(XGraphics gfx, Boolean topLevel) at MigraDoc.Rendering.FormattedDocument.Format(XGraphics gfx) at MigraDoc.Rendering.DocumentRenderer.PrepareDocument() at MigraDoc.Rendering.PdfDocumentRenderer.PrepareDocumentRenderer(Boolean prepareCompletely) at MigraDoc.Rendering.PdfDocumentRenderer.PrepareRenderPages() at MigraDoc.Rendering.PdfDocumentRenderer.RenderDocument() at Invoicer.Services.Impl.PdfInvoice.Save(String filename, String password)

The specified file has no valid PDF file header

Hi,

I'm using your PdfSharp. It really awesome because working with .Net Core.

But now I get an error like below:
ArgumentException: The specified file has no valid PDF file header. Parameter name: path

It happen when using below code:
XPdfForm form = XPdfForm.FromFile(filePath);

I check in the code, I suspect it because of the files in the PdfReader at line 162 like below:
string header = PdfEncoders.RawEncoding.GetString(bytes, 0, bytes.Length);

Whenever I using this, it always return PDF version as 0. So when I try using original code string header = Encoding.ASCII.GetString(bytes);, it working like charm, it will return with PDF version.

So, how do fix this? Or do you have suggestion for this? Or you can replace it using this below code
string header = Encoding.ASCII.GetString(bytes);

System.IO.DirectoryNotFoundException when querying GlobalFontSettings.FontResolver

I use the PDFSharpCore lib in my Xamarin Forms App for iOS and Android. After countless tries with other libs, this one works. But there is a samll problem with the FontResolver that should be fixed.

I use my own fonts. The fonts are embedded in the shared project as EmbeddedRessource. To load them I implemented my pwn FontResolver.

But when I query for an already existant FontResolver, I get an DirectoryNotFoundException.

System.IO.DirectoryNotFoundException: 'Could not find a part of the path '/Library/Fonts'.'

// Init the own FontResolver if not done before
if (GlobalFontSettings.FontResolver == null)
{
        GlobalFontSettings.FontResolver = new FontResolver();
}

In the if statement above the DirectoryNotFoundException gets thrown. The reason is:
In the getter of GlobalFontSettings.FontResolver an implementation of FontResolver is automatically created, if no resolver is already existant. And this one wants to have a Folder '/Library/Fonts'.

I resolved it by removing the if statement and manually checking if I already assigned my own FontResolver.

I'm not sure what's the best solution for this. But in my opinion there should not be created a standard FontResolver in the getter of GlobalFontSettings.Fontresolver.

Edit:
On Android (7.0) the DirectoryNotFoundException looks like this:

System.IO.DirectoryNotFoundException: 'Could not find a part of the path '/usr/share/fonts/truetype'.'

On iOS (13.x) the DirectoryNotFoundException looks like this:

System.IO.DirectoryNotFoundException: 'Could not find a part of the path '/Library/Fonts'.'

Create table

I will try to use PdfSharp with NetCore 3.1.
There is a method to create easy a table?
The function of migradoc are not included in these version for netcore?

Thanks

Spaces between words

Hi, I'm converting an application from PdfSharp Library to PdfSharpCore, it is a large application, but all texts now have a different space size between words (see image attached) comparing the same string on PdfSharpCore and PdfSharp. Is there any solution to this issue? Thank you.

pdfsharpcore

Issue with FontResolver on iOS

Hello,

I try to use PdfSharpCore on iOS to fill AcroForm.
No problem on Window, but when I try on iPad this issues appear:

System.InvalidOperationException: Sequence contains no elements
at System.Linq.Enumerable.First[TSource] (System.Collections.Generic.IEnumerable`1[T] source)
at PdfSharpCore.Utils.FontResolver.ResolveTypeface (System.String familyName, System.Boolean isBold, System.Boolean isItalic)
at PdfSharpCore.Fonts.FontFactory.ResolveTypeface (System.String familyName, PdfSharpCore.Fonts.FontResolvingOptions fontResolvingOptions, System.String typefaceKey)

Someone have an idea about that? Because I don't know how to fix it.

Best regards,
Alexis

AddPage does not clone Annotations

This is a bug that was in PDFSharp. See this link.

Line 444 in PdfPages.cs needs to be uncommeted.
CloneElement(page, importPage, PdfPage.Keys.Annots, false);

Search by Arial is returning Arial Bold instead of Arial on Ubuntu

Font search's is considering the first occuring of related names to font name passed by parameter.
A cenario that i catched it is in a search by Arial on Ubuntu was returning Arial Bold instead of Arial.

To correct it i suggest to change method ResolveTypeface of class PdfSharpCore.Utils.FontResolver to it:

    public FontResolverInfo ResolveTypeface(string familyName, bool isBold, bool isItalic)
    {
        string ttfFile = fontfaceTofontfileMap.Keys.First(),
            tf, fontkey;

        familyName = familyName.ToLower();

        fontkey = familyName;
        if (isBold) fontkey += "b";
        if (isItalic) fontkey += "i";

        if (!fontfamilyTofontfaceMap.TryGetValue(fontkey, out ttfFile))
        {
            foreach (string fontfile in fontfaceTofontfileMap.Keys)
            {
                tf = Path.GetFileNameWithoutExtension(fontfile).ToLower().TrimEnd('-', '_');

                if (tf == familyName)
                {
                    ttfFile = fontfile;

                    if (isBold && isItalic)
                    {
                        if ((tf.Contains("bold") && tf.Contains("italic")) || (tf.EndsWith("bi", StringComparison.Ordinal) || tf.EndsWith("ib", StringComparison.Ordinal)))
                        {
                            ttfFile = fontfile;
                            break;
                        }
                    }
                    else if (isBold)
                    {
                        if (tf.Contains("bold") || tf.EndsWith("b", StringComparison.Ordinal) || tf.EndsWith("bd", StringComparison.Ordinal))
                        {
                            ttfFile = fontfile;
                            break;
                        }
                    }
                    else if (isItalic)
                    {
                        if (tf.Contains("italic") || tf.EndsWith("i", StringComparison.Ordinal) || tf.EndsWith("ib", StringComparison.Ordinal))
                        {
                            ttfFile = fontfile;
                            break;
                        }
                    }
                    else
                    {
                        //We found a match on this font and did not want bold or italic.
                        //This is not guaranteed to always be correct, but the first matching key is usually the normal variant.
                        break;
                    }
                }
            }
            if (string.IsNullOrWhiteSpace(ttfFile))
            {
                foreach (string fontfile in fontfaceTofontfileMap.Keys)
                {
                    tf = Path.GetFileNameWithoutExtension(fontfile).ToLower().TrimEnd('-', '_');

                    if (tf.Contains(familyName))
                    {
                        ttfFile = fontfile;

                        if (isBold && isItalic)
                        {
                            if ((tf.Contains("bold") && tf.Contains("italic")) || (tf.EndsWith("bi", StringComparison.Ordinal) || tf.EndsWith("ib", StringComparison.Ordinal)))
                            {
                                ttfFile = fontfile;
                                break;
                            }
                        }
                        else if (isBold)
                        {
                            if (tf.Contains("bold") || tf.EndsWith("b", StringComparison.Ordinal) || tf.EndsWith("bd", StringComparison.Ordinal))
                            {
                                ttfFile = fontfile;
                                break;
                            }
                        }
                        else if (isItalic)
                        {
                            if (tf.Contains("italic") || tf.EndsWith("i", StringComparison.Ordinal) || tf.EndsWith("ib", StringComparison.Ordinal))
                            {
                                ttfFile = fontfile;
                                break;
                            }
                        }
                        else
                        {
                            //We found a match on this font and did not want bold or italic.
                            //This is not guaranteed to always be correct, but the first matching key is usually the normal variant.
                            break;
                        }
                    }
                }
            }

            fontfamilyTofontfaceMap.Add(fontkey, ttfFile);
        }

        if (ttfFile == null) ttfFile = fontfaceTofontfileMap.Keys.First();
        return new FontResolverInfo(ttfFile);
    }

read a pdf is error.

position:PdfSharpCore.Pdf.IO.Parser.ReadXRefTableAndTrailer(PdfCrossReferenceTable xrefTable)

        private PdfTrailer ReadXRefTableAndTrailer(PdfCrossReferenceTable xrefTable)
        {
            Debug.Assert(xrefTable != null);

            Symbol symbol = ScanNextToken();/// return  Keyword

DrawImage() on iOSDevice

I'm trying to create a PDF in an iOS app using Xamarin, and it works fine on the simulator but running on a device gives this error:

Attempting to JIT compile method 'SixLabors.ImageSharp.Formats.Png.PngDecoderCore:ProcessDefilteredScanline<SixLabors.ImageSharp.PixelFormats.Rgba32> (System.ReadOnlySpan1<byte>,SixLabors.ImageSharp.ImageFrame1<SixLabors.ImageSharp.PixelFormats.Rgba32>)' while running in aot-only mode. See https://docs.microsoft.com/xamarin/ios/internals/limitations for more information.

This is triggered by calling the DrawImage() function, here's how I'm using it:

var page = document.AddPage();
page.Size = PageSize.A4;
var gfx = XGraphics.FromPdfPage(page);
XImage image = XImage.FromFile("icon.jpg");
gfx.DrawImage(image, new XRect(55, 767, 56, 37));

System.IO.FileNotFoundException exception in linux ( Ubuntu 16.04)

Hi,
I take the error as below in linux :
Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'PdfSharpCore, Version=1.1.18.0, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.

But dll file is in the app folder. Do you have any idea?

Thank you.

Cannot draw an image (jpeg)

Hi, Im trying to draw an image (jpg) to pdf using pdfsharpcore. Below is my code.

        PdfDocument document = new PdfDocument();
        PdfPage page = document.AddPage();
        XGraphics gfx = XGraphics.FromPdfPage(page);
        XImage image = XImage.FromFile("D:\\imageFile.jpg");

        // draw image to pdf
        gfx.DrawImage(image, 0, 0, 250, 140);

        // Save the document...
        string filename = "D:\\test.pdf";
        document.Save(filename);

But it not working, it gave me an error. Can anyone help me?
Here I attach the error.
1

NuGet packages for MigraDoc

It seems this fork of PdfSharp is very popular, it would be great if you could build a NuGet package for MigraDoc as well, so we'll have a complete set. Thanks!

MigraDoc Styles not applied properly

When using Migradoc, all document styles appear to combined and the resulting PDF has a single font definition. Example code:

        Document currentDoc = new Document();
        DocumentRenderer renderer = new DocumentRenderer(currentDoc);
        Style normal = currentDoc.Styles["Normal"];
        normal.Font.Name = "Tahoma";
        normal.Font.Size = 10;
        normal.Font.Color = new Color(0, 0, 0);
        normal.Font.Bold = false;
        normal.Font.Italic = false;

        Style boldCap = currentDoc.Styles.AddStyle("BoldCaption", "Normal");
        boldCap.Font.Name = "Tahoma";
        boldCap.Font.Size = 10;
        boldCap.Font.Color = new Color(0, 0, 0);
        boldCap.Font.Bold = true;
        boldCap.Font.Italic = false;

        Section section = currentDoc.AddSection();
        section.PageSetup.Orientation = Orientation.Landscape;
        section.PageSetup.LeftMargin = Unit.FromInch(0.5);
        section.PageSetup.BottomMargin = Unit.FromInch(0.5);
        section.AddParagraph("This should be bold", boldCap.Name);
        section.AddParagraph("This is just normal", normal.Name);
        renderer.PrepareDocument();

        PdfDocument pdf = new PdfDocument();
        PdfPage page = pdf.AddPage();
        var gfx = XGraphics.FromPdfPage(page);
        renderer.RenderPage(gfx, 1, PageRenderOptions.All);
        pdf.Save("test.pdf");

Output:
image
Expected output: The normal style should not be bold.

I'm currently looking into this, but I wanted to post it here so it's documented and maybe someone already knows what's wrong.

P.S. This should be .NET Standard so it can be referenced from class libraries, not just application projects directly. .NET Core can only be referenced by .NET Core projects, Standard can be referenced from all projects. @onizet submitted a pull request for that change in December, it's probably worth using unless there's something wrong with it.

Threading issue GlyphTypefaceCache Dictionary

I'm creating pdfs from a web service and it looks like there might be an issue with multi-threading for the dictionary in GlyphTypefaceCache. Currently, I can only reproduce it sometimes while running tests, probably due to the race condition nature of it. I understand Dictionaries aren't thread-safe so I wonder if it's something that should be replaced by something like ConcurrentDictionary.

Here's the stacktrace:

Stack Trace:
   at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior)
   at PdfSharpCore.Fonts.OpenType.GlyphTypefaceCache.AddGlyphTypeface(XGlyphTypeface glyphTypeface)
   at PdfSharpCore.Drawing.XGlyphTypeface.GetOrCreateFrom(String familyName, FontResolvingOptions fontResolvingOptions)
   at PdfSharpCore.Drawing.XFont.Initialize()```

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.