cannot open my RTF file with my custom fonts - c#

I made my own custom .ttf fonts for my UWP program and put them in Assets folder (vs 2017/2019). They are working well when the Document is processed in RichEditBox. However, when I Save the RTF file and then Open it, my custom fonts are ignored. If I install my custom fonts beforehand into Windows\Fonts folder , then Open file load the document with my custom fonts. Looks like without installing my custom fonts the program does not link them to the document.
Again - I wrote a program with RichEditBox and my custom fonts in that program. When processed - fonts changed, styles changed, etc - everything goes as designed. When I save RTF file with that program, and open that RTF with that (the same) program - color table is OK but my fonts are not shown though the fonts were compiled with that program (BuildAction - Content; CopyToOutputDirectory - Copy always). To simplify - I made button with the information the file contains. Though fonts are compiled (located in Assets folder), the program does not link them to the document.
Actually with that button I tried to reproduce what is described here: RichEditBox (UWP) ignores font and foreground when setting Rtf text However in my case, the RichEditBox shows only fonts installed in Windows\Fonts directory. How to overcome that and either use links to local fonts compiled with my program or make installer install the fonts to Windows\Fonts directory?
How could I use my custom fonts (link them to the document) without installing them or what I need to do my UWP program installs my custom fonts to user's device while installing itself?
This is code for button I used to display text:
private void Page_Click(object sender, RoutedEventArgs e)
{
string myRtfString = #"{\rtf1\fbidis\ansi\ansicpg1252\deff0\nouicompat\deflang1033{\fonttbl{\f0\fnil MyFont;}{\f1\fnil MyFont1;}{\f2\fnil MyFont2;}} {\colortbl ;\red0\green0\blue0;\red255\green255\blue255;\red255\green100\blue0;} {\*\generator Riched20 10.0.18362}\viewkind4\uc1 \pard\sl480\slmult1\qj\cf1\highlight2\f0\fs36 tt\highlight3\f1 g\f0 acgt\f2 c\highlight2\f0 tt\highlight0\par}";
editor.Document.SetText(TextSetOptions.FormatRtf, myRtfString);
}
This is XAML for RichEditBox:
<RichEditBox
x:Name="editor"
Height="200"
FontFamily="Assets/Fonts/MyFont.ttf#MyFont"
FontSize="24" RelativePanel.Below="openFileButton"
RelativePanel.AlignLeftWithPanel="True"
RelativePanel.AlignRightWithPanel="True" />

Gosha, this way you can apply at least one of the fonts to that .rtf file - see below. For others, I think, you need to use either map information from that .rtf or make an additional map of your own. That will be some "trabajo", but what can you do?
private void applyMyFonts()
{
string TextOut;
MyRichEditBox.Document.GetText(TextGetOptions.None, out TextOut);
MyRichEditBox.Document.Selection.SetRange(0, TextOut.Length);
MyRichEditBox.Document.Selection.CharacterFormat.Name = "Assets/Fonts/MyFont.ttf#MyFont";
}
private async void OpenButton_Click(object sender, RoutedEventArgs e)
{
Windows.Storage.Pickers.FileOpenPicker open =
new Windows.Storage.Pickers.FileOpenPicker();
open.SuggestedStartLocation =
Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
open.FileTypeFilter.Add(".rtf");
Windows.Storage.StorageFile file = await open.PickSingleFileAsync();
if (file != null)
{
try
{
Windows.Storage.Streams.IRandomAccessStream randAccStream =
await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
// Load the file into the Document property of the RichEditBox.
MyRichEditBox.Document.LoadFromStream(Windows.UI.Text.TextSetOptions.FormatRtf, randAccStream);
}
catch (Exception)
{
ContentDialog errorDialog = new ContentDialog()
{
Title = "File open error",
Content = "Sorry, I couldn't open the file.",
PrimaryButtonText = "Ok"
};
await errorDialog.ShowAsync();
}
}
applyMyfonts();
}

Related

Outlook VSTO code crashes when click on the button for image

I am working on this Outlook VSTO Add-on, to add an image in the body of the email, but no luck at all for two weeks!!! It works with a normal path like c:\folder
but it doesn't work if I want to use the Resources folder inside of the app.
When I run it and click on the button, it crashes and goes to the:
document.Application.Selection.InlineShapes.AddPicture(ImagePath);
There is a Ribbon with a button. When user clicks, it should add the email signature in the body.
PLEASE HELP!!!!!!!!!!!!!!!!
private void button_Click(object sender, RibbonControlEventArgs e)
{
Outlook.Inspector inspector = Globals.ThisAddIn.Application.ActiveInspector();
Word.Document document = inspector.WordEditor;
string ImagePath = #"\Resources\Picture.jpg";
if (document.Application.Selection == null)
{
MessageBox.Show("Please select the email body");
}
else
{
document.Application.Selection.InlineShapes.AddPicture(ImagePath);
}
}
Word Object Model knows nothing about resources inside your assembly. It does not know and does not care about any external assemblies. It only understands files - you will need to extract the resource into a temp file and specify that file's fully qualified file name.

PDF file isn't centered in webBrowser control of Windows Form

I'm trying to make a PDF utility app that will allow users to merge and split PDF files. The only problem I have right now is that on load my app shows the pdf file off center. Example
In order to make the PDF file center I have to manually mouse-click the dark grey area that is shown when the PDF file is off center. After that the pdf file will be center like so
So is there anyway possible to make the PDF file centered automatically like the 2nd image?
Code below is how I call webBrowser1 that is rendering the pdf file.
public Form1()
{
InitializeComponent();
string filename = "pdf_example.pdf";
string path = Path.Combine(Environment.CurrentDirectory, filename); // grab pdf file from root program file
webBrowser1.Url = new Uri(path); // <-- input pdf location, WebBrowser Code section, REDACTED
//"button1" == "Load PDF Files", EventHandler
button1.Click += new EventHandler(button1_click);
//"button2" == "Save PDF Files", EventHandler
button2.Click += new EventHandler(button2_click);
//"button3" == "Merge PDF Files", EventHandler
button3.Click += new EventHandler(button3_click);
//"button4" == "Split PDF Files", EventHandler
button4.Click += new EventHandler(button4_click);
}
I was thinking it had to do with the pdf being loaded before the Form1 window was completely loaded. So I tried making a method and set Form1 Shown properties to this method.
void Form1_Shown(object sender, EventArgs e)
{
string filename = "pdf_example.pdf";
string path = Path.Combine(Environment.CurrentDirectory, filename); // grab pdf file from root program file
webBrowser1.Url = new Uri(path); // <-- input pdf location, WebBrowser Code section, REDACTED
}
It didn't work.
Any help would be much appreciated.
Also I completely redid the app to use axAcroPDF control to render PDF instead of webBrowser control to render PDF and I still got the same problem where the PDF file was off-center.
For future reference. The problem was that my monitor resolution was set to 4k. This caused the pdf file to be open off center in IE every-time for some reason. If the program was open in a 1920x1080 resolution monitor then the pdf file is perfectly centered every-time the program starts.

How build link to local file in richtextbox

Hello i builded application with log that sow me what i am doing(where i saving files).
Sow my goal here is build links to all my new files that i created and open them by click
This my code
StreamWriter sw = new StreamWriter(Path.Combine(filepath), false, Encoding.GetEncoding("Windows-1255"));
sw.Write(Encoding.GetEncoding("Windows-1255").GetString(byteArray1255));
sw.Close();
rtx_Log.Text+= filepath;
here i created some file and i just want to show the pass in richtextbox and open it by click.
If RichTextBox.DetectUrls is set to true, the control will automatically detect links from the protocol and create a link.
"My File: file://c:/MyFile.txt" will display the file:// part as a link.
The RichTextBox.LinkClicked event is fired when the user clicks a link - and you can act on it as needed.
private void RichTextBox1OnLinkClicked(object sender, LinkClickedEventArgs e)
{
var filePath = new Uri(e.LinkText).AbsolutePath;
}

Prevent webbrowser from formating html file in c#

I have some trouble using the webbrowser control in C#, especially when I print it. The thing is, I have a Barcode in my html file and I have to print it (I use a font to create the code). When I open the html file with Firefox or any other Web browser, my barecode is good and I can scan it. But, when I open my file with my webbrowser in c#, or when I print it, the webbrowser ad 2 characters after the barecode. And, when I print the file, my document is not centered, it's like the webbrowser add a margin-left property. So my question is, is there any way to print an html file, using a webbroser, exactly how I see the html file when I use firefox or chrome for example. Here is the code I use.
curDir = Directory.GetCurrentDirectory();
webBrowserA4.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(PrintDocument);
webBrowserA4.Url = new Uri(String.Format("file:///{0}/print.html", curDir));
private void PrintDocument(object sender, WebBrowserDocumentCompletedEventArgs e)
{
// Print the document now that it is fully loaded.
((WebBrowser)sender).Print();
// Dispose the WebBrowser now that the task is complete.
((WebBrowser)sender).Dispose();
}
EDIT: So, now, I have another problem, here is the screen of what my file looks like when I print it: http://imgur.com/q7ovEA1 As you can see, there is a "margin-left", and I can't remove it. I also want to remove this "page 1 of 1" and the Title.

how to print .htm files in c#?

I can't seem to find a good way to print .htm files in c# using .net 4.0, visual studio 2010 and windows forms. When i tried to print it directly, it printed the raw html data instead of printing the "page" itself.
The only way i know to print it, is to use a WebBrowser control. When i print the document, it doesn't print colors and the page isn't printed correctly. For example, the edges are not drawn and so on.
Code for Web Browser :
public void Print()
{
// Create a WebBrowser instance.
WebBrowser webBrowserForPrinting = new WebBrowser();
// Add an event handler that prints the document after it loads.
webBrowserForPrinting.DocumentCompleted +=
new WebBrowserDocumentCompletedEventHandler(PrintDocument);
// Set the Url property to load the document.
webBrowserForPrinting.Url = new Uri(Core.textLog);
}
private void PrintDocument(object sender, WebBrowserDocumentCompletedEventArgs e)
{
((WebBrowser)sender).ShowPrintDialog();
//// Print the document now that it is fully loaded.
//((WebBrowser)sender).Print();
//// Dispose the WebBrowser now that the task is complete.
((WebBrowser)sender).Dispose();
}
What can i do?
Thank you!
Printing web pages will forever be the bane of your existence. There just isn't a solution out there that prints HTML directly to your printer really, really well. And even if you do find a program that does it well, it's only a matter of time until you try to print a page with some unsupported formatting, in which case you're right back where you started.
What we do is print HTML to a pdf file with a program called wkhtmltopdf. Then we open it in Acrobat (which has excellent printing support) and print from there. I can't say enough good things about wkhtmltopdf. It's command line driven, and its super, super fast. Best of all, its free. It has a companion program called wkhtmltoimage that will print to most popular image formats, too (bmp, jpg, png, etc).
After downloading/installing the program, you can run a quick test by going to your command prompt, navigating to the install folder, and typing:
wkhtmltopdf "http://YouWebAddress.com" "C:/YourSaveLocation.pdf"
It also has a ton of command line switches that give you greater control over the outputs (headers, footers, page numbering, etc etc).
Ok, as i said, problem was that edge are not drawn and neither are the backgrounds.
Here is how i solved it.
Hashtable values = new Hashtable();
values.Add("margin_left", "0.1");
values.Add("margin_right", "0.1");
values.Add("margin_top", "0.1");
values.Add("margin_bottom", "0.1");
values.Add("Print_Background", "yes");
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(#"Software\Microsoft\Internet Explorer\PageSetup", true))
{
if (key == null) return;
foreach (DictionaryEntry item in values)
{
string value = (string)key.GetValue(item.Key.ToString());
if (value != item.Value.ToString())
{
key.SetValue(item.Key.ToString(), item.Value);
}
}
}
So before i print, i go to regedit, change the values, and the document gets printed perfectly. Hope this helps other people that have the same problem when printing from webbrowser control in windows forms.

Categories