MigraDox C# Checkboxes - Wingdings Not Working - c#

I am needing to simulate a checkbox in a PDF I am generating using the MigraDoc library. I stumbled across two sources that offer essentially the same solution (here and here)
However, I am not getting the expected results. Instead I am getting þ for boxes that are supposed to be checked, and ¨ for those that are to be unchecked. What might the issue be?
Snippet of my code
para = section.AddParagraph();
para.Style = "ListLevelOne";
para.AddFormattedText("1 ", "Bold");
para.AddFormattedText(IsQ1Checked ? "\u00fe" : "\u00A8", new Font("Wingdings"));

MigraDoc does not use the font "Wingdings", instead it uses a default font (could be MS Sans or so) and therefore you see the characters from a standard font, not the Wingdings symbol.
The problem is somewhere outside the code snippet you are showing here. Make sure the font Wingdings is installed on the computer.

You may want to embed the font and ensure that MigraDoc uses unicode encoding instead of ansi:
private const bool unicode = true;
private const PdfFontEmbedding embedding = PdfFontEmbedding.Always;
//...
var pdfRenderer = new PdfDocumentRenderer(unicode, embedding);
http://www.pdfsharp.net/wiki/migradochelloworld-sample.ashx

Related

c# , how to generate password protected arabic pdf or word document

I used Itext7 in my C# code to create a pdf file, as I said in my other question here
Itext7 not showing arabic text
so I gave up on trying to fix it, because it seems like I need to pay for the addon, and I can't do that
I tried Pdf sharp, it showed arabic letters but there were disconnected and reversed, and writing arabic backward did not make the letters connect
I used SautinSoft library and it created a word document where arabic works fine, but it has a footer that says that it is a free version, so i can't use this one either
the pdf created by this library also doesnt support arabic
so I think I can't write pdf in arabic, all libraries I tried didn't supported it
is there anyway to fix it?
or can anyone please suggest another library that can create arabic pdf or a word document without watermarks or footers
I found the solution, using Gembox pdf, it only allows 20 paragraphs, but that is more than enough
What if DocumentCore?
public static void SecureDocument()
{
string filePath = #"ProtectedDocument.pdf";
DocumentCore dc = new DocumentCore();
// Let's create a simple document.
dc.Content.End.Insert("Hello World!!!", new CharacterFormat() { FontName = "Verdana", Size = 65.5f, FontColor = Color.Orange });
PdfSaveOptions so = new PdfSaveOptions();
// Password Protection
so.EncryptionDetails.UserPassword = "12345";
// EncryptionAlgorithm
so.EncryptionDetails.EncryptionAlgorithm = PdfEncryptionAlgorithm.RC4_128;
//Permissions: Content Copying, Commenting, Printing, Changing the Document, filing of form fildes
//Printing: Allowed
so.EncryptionDetails.Permissions = PdfPermissions.Printing;
// Save a document as the PDF file with Security Options.
dc.Save(filePath, so);
// Open the result for demonstration purposes.
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(filePath) { UseShellExecute = true });
}

Exporting WPF Canvas to PDF

I've been attempting to find an easy solution to exporting a Canvas in my WPF Application to a PDF Document.
So far, the best solution has been to use the PrintDialog and set it up to automatically use the Microsoft Print the PDF 'printer'. The only problem I have had with this is that although the PrintDialog is skipped, there is a FileDialog to choose where the file should be saved.
Sadly, this is a deal-breaker because I would like to run this over a large number of canvases with automatically generated PDF names (well, programitically provided anyway).
Other solutions I have looked at include:
Using PrintDocument, but from my experimentation I would have to manually iterate through all my Canveses children and manually invoke the correct Draw method (of which a lot of my custom elements with transformation would be rather time consuming to do)
Exporting as a PNG image and then embedding that in a PDF. Although this works, TextBlocks within my canvas are no longer text. So this isn't an ideal situation.
Using the 3rd party library PDFSharp has the same downfall as the PrintDocument. A lot of custom logic for each element.
With PDFSharp. I did find a method fir generating the XGraphics from a Canvas but no way of then consuming that object to make a PDF Page
So does anybody know how I can skip or automate the PDF PrintDialog, or consume PDFSharp XGraphics to make
A page. Or any other ideas for directions to take this besides writing a whole library to convert each of my Canvas elements to PDF elements.
If you look at the output port of a recent windows installation of Microsoft Print To PDF
You may note it is set to PORTPROMP: and that is exactly what causes the request for a filename.
You might note lower down, I have several ports set to a filename, and the fourth one down is called "My Print to PDF"
So very last century methodology; when I print with a duplicate printer but give it a different name I can use different page ratios etc., without altering the built in standard one. The output for a file will naturally be built:-
A) Exactly in one repeatable location, that I can file monitor and rename it, based on the source calling the print sequence, such that if it is my current default printer I can right click files to print to a known \folder\file.pdf
B) The same port can be used via certain /pt (printto) command combinations to output, not just to that default port location, but to a given folder\name such as
"%ProgramFiles%\Windows NT\Accessories\WORDPAD.EXE" /pt listIN.doc "My Print to PDF" "My Print to PDF" "listOUT.pdf"
Other drivers usually charge for the convenience of WPF programmable renaming, but I will leave you that PrintVisual challenge for another of your three wishes.
MS suggest XPS is best But then they would be promoting it as a PDF competitor.
It does not need to be Doc[X]2PDF it could be [O]XPS2PDF or aPNG2PDF or many pages TIFF2PDF etc. etc. Any of those are Native to Win 10 also other 3rd party apps such as [Free]Office with a PrintTo verb will do XLS[X]2PDF. Imagination becomes pagination.
I had a great success in generating PDFs using PDFSharp in combination with SkiaSharp (for more advanced graphics).
Let me begin from the very end:
you save the PdfDocument object in the following way:
PdfDocument yourDocument = ...;
string filename = #"your\file\path\document.pdf"
yourDocument.Save(filename);
creating the PdfDocument with a page can be achieved the following way (adjust the parameters to fit your needs):
PdfDocument yourDocument = new PdfDocument();
yourDocument.PageLayout = PdfPageLayout.SinglePage;
yourDocument.Info.Title = "Your document title";
PdfPage yourPage = yourDocument.AddPage();
yourDocument.Orientation = PageOrientation.Landscape;
yourDocument.Size = PageSize.A4;
the PdfPage object's content (as an example I'm putting a string and an image) is filled in the following way:
using (XGraphics gfx = XGraphics.FromPdfPage(yourPage))
{
XFont yourFont = new XFont("Helvetica", 20, XFontStyle.Bold);
gfx.DrawString(
"Your string in the page",
yourFont,
XBrushes.Black,
new XRect(0, XUnit.FromMillimeter(10), page.Width, yourFont.GetHeight()),
XStringFormats.Center);
using (Stream s = new FileStream(#"path\to\your\image.png", FileMode.Open))
{
XImage image = XImage.FromStream(s);
var imageRect = new XRect()
{
Location = new XPoint() { X = XUnit.FromMillimeter(42), Y = XUnit.FromMillimeter(42) },
Size = new XSize() { Width = XUnit.FromMillimeter(42), Height = XUnit.FromMillimeter(42.0 * image.PixelHeight / image.PixelWidth) }
};
gfx.DrawImage(image, imageRect);
}
}
Of course, the font objects can be created as static members of your class.
And this is, in short to answer your question, how you consume the XGraphics object to create a PDF page.
Let me know if you need more assistance.

HTML to PDF in a Windows universal app (UWP)

Is it possible to convert an HTML string to a PDF file in a UWP app?
I've seen lots of different ways it can be done in regular .NET apps (there seem to be plenty of third party libraries), but I've yet to see a way it can be done in a Universal/UWP app. Does anyone know how it can be done?
Perhaps there is some way to hook into the "Microsoft Print to PDF" option, if there is no pure code solution?
Or is there a roundabout way of doing it, maybe like somehow using Javascript and https://github.com/MrRio/jsPDF inside a C# UWP app? I'm not sure, clutching at straws...
EDIT
I have marked the solution provided by Grace Feng - MSFT as correct for proving that it IS possible to convert HTML to PDF, through the use of the Microsoft Print to PDF option in the print dialog. Thank you
Perhaps there is some way to hook into the "Microsoft Print to PDF" option, if there is no pure code solution?
Yes, but using this way, you will need to firstly show your HTML string in controls like RichEditBox or TextBlock, only UIElement can be printable content.
You can also create PDF file by yourself, here is basic syntax used in PDF:
You can use BT and ET to create paragraph:
Here is sample in C#:
StringBuilder sb = new StringBuilder();
sb.AppendLine("BT"); // BT = begin text object, with text-units the same as userspace-units
sb.AppendLine("/F0 40 Tf"); // Tf = start using the named font "F0" with size "40"
sb.AppendLine("40 TL"); // TL = set line height to "40"
sb.AppendLine("230.0 400.0 Td"); // Td = position text point at coordinates "230.0", "400.0"
sb.AppendLine("(Hello World)'");
sb.AppendLine("/F2 20 Tf");
sb.AppendLine("20 TL");
sb.AppendLine("0.0 0.2 1.0 rg"); // rg = set fill color to RGB("0.0", "0.2", "1.0")
sb.AppendLine("(This is StackOverflow)'");
sb.AppendLine("ET");
Then you can create a PDF file and save this into this file. But since you want to convert the HTML to PDF, it could be a hard work and I think you don't want to do this.
Or is there a roundabout way of doing it, maybe like somehow using Javascript and https://github.com/MrRio/jsPDF inside a C# UWP app? I'm not sure, clutching at straws...
To be honestly, using Libs or Web service to convert HTML to PDF is also a method, there are many and I just searched for them, but I can't find any free to be used in WinRT. So I think the most practicable method here is the first one, hooking into Microsoft Print to PDF. To do this, you can check the official Printing sample.
Update:
Used #Jerry Nixon - MSFT's code in How do I print WebView content in a Windows Store App?, this is a great sample. I just added some code for add pages for printing, in the NavigationCompleted event of WebView:
private async void webView_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
{
MyWebViewRectangle.Fill = await GetWebViewBrush(webView);
MyPrintPages.ItemsSource = await GetWebPages(webView, new Windows.Foundation.Size(842, 595));
}
Then in the printDoc.AddPages += PrintDic_AddPages; event (printDoc is instance of PrintDocument):
private void PrintDic_AddPages(object sender, AddPagesEventArgs e)
{
foreach (var item in MyPrintPages.Items)
{
var rect = item as Rectangle;
printDoc.AddPage(rect);
}
printDoc.AddPagesComplete();
}
For other code you can refer to the official printing sample.

Fonts don't load in the pdf viewer

I have currently a problem with PdfSharp/MigraDoc and a pdf viewer. I have used the EZFontResolver made by Thomas to be able to generate pdfs with custom fonts. Unfortunately the pdf viewer is unable to render the font, and I have no idea why. I have seen a bug described by Travis on Thomas' blog, which noted, that if EZFontResolver doesn't have multiple bold/italic symbol recognition (for example "fontname|b|b"), than PdfDocumentRenderer.RenderDocument() fails. The point is, when I try something like this:
Document document = DdlReader.DocumentFromString(ddl);
_renderer = new DocumentRenderer(document);
_renderer.PrepareDocument();
than the EZFontResolver is being asked for fonts with names like "customfont|b|b" (it doesn't happen when I use only PdfDocument.Save(...)) instead of "customfont".
My pdf viewer overrides DocumentViewer and views FixedDocument class instances. The funny thing is that the saved pdf file has all the fonts set, but the preview is unable to do that (and that is my big problem). All of this happens even though I return the right font with the resolver.
EDIT:
The ddl is a string which looks something like this:
"\\document
[
Info
{
Title = \"My file\"
Subject = \"My pdf file\"
Author = \"mikes\"
}
]
{
\\styles
{
Heading1 : Normal
{
Font
{
Name = \"My custom font\"
Bold = true
}
ParagraphFormat
{
Alignment = Center
SpaceBefore = \"0.5cm\"
SpaceAfter = \"0.5cm\"
}
}
header : Normal
{
Font
{
Name = \"My custom font\"
Size = 6
}
ParagraphFormat
{
Alignment = Center
}
}
And when I deleted the bug fix by Travis, the exception was thrown in the _renderer.PrepareDocument() (after fix, the stack trace showed that the source of multiple "|b" was also out of there).
Simulated bold and simulated italics use the regular font, but a transformation is applied.
Therefore the simulation will not work if the PDF viewer does not support those transformations.
The DocumentViewer that comes with MigraDoc does not display PDF files, it displays MigraDoc documents. For technical reasons it cannot use fonts supplied via the IFontResolver interface. EZFontResolver is an implementation of IFontResolver.
With respect to "customfont|b|b": I cannot say whether this is a bug or the regular behaviour. Please provide an MCVE (complete sample) if you think it is a bug.

Saving PDF with cyrillic text in Unity3D using iTextSharp

I create a BaseFont using that code
string combineStr = Path.Combine(Application.dataPath+"/Resources/Fonts", "Calibri Regular.ttf");
BaseFont bf = BaseFont.CreateFont(combineStr, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
iTextSharp.text.Font titleFont = new iTextSharp.text.Font(bf, 10f, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
Testing it in Unity everything works fine, and my cyrillic glyphs working well, but in WindowsPalyer build i get an error
ArgumentException: Encoding name 'windows-1252' not supported
Paremeter name: name.
Cant find any problem here.. Checked everything, and how I see my BaseFont code is correct. What is wrong in my case?
P.S. I have tried also others fonts with cyrillic support, but nothing helps.
The OP added the solution to the question. I'm removing it from the question, adding it as a real answer:
The issue here is that I18N.dll and I18N.West.dll are missing in the standalone player.They are available in the editor, though. That's why it's working in the editor but not in the standalone player.
Solution: Put those DLLs into your project (probably best next to System.Data.dll), that way, they will be also available in the standalone player.
See also CodePage 1252 not supported - works in editor but not in standalone player on Unity Answers.

Categories

Resources