Im using the TX TextEditingControl (free version) and I think this is absolutely great.
But I cant seem to get the RTF (Text) content that I need.
//Define
private TXTextControl.TextControl rtf = new TXTextControl.TextControl();
[...code...]
private void button_Click(object sender, EventArgs e) {..
//rtf.Save(s, TXTextControl.StreamType.RichTextFormat);
//This is what I would like to do but I cant find the property or function that does this.
string s = rtf.DocumentRTF;
//Im expecting the standard RTF Format but I get blank
MessageBox.Show(s);
}
Found it! There is no RTF property, to get the output you must use the save() function. Luckily you can write to streams and strings.
string s = "";
rtf.Selection.Bold = true;
//rtf.Selection.Save(TXTextControl.StreamType.RichTextFormat);
rtf.Save(out s,TXTextControl.StringStreamType.RichTextFormat);
MessageBox.Show(s);
dear use the following
for Vb.Net
Dim RegFont As New Font("Arial", UseFontSize, FontStyle.Bold)
Dim VIPFont As New Font("Arial", UseFontSize, FontStyle.Bold)
MyRitchText.SelectionFont = VIPFont
MyRitchText.SelectionAlignment = HorizontalAlignment.Center
MyRitchText.SelectionColor = Color.Green
for c#
Font RegFont = new Font("Arial", UseFontSize, FontStyle.Bold);
Font VIPFont = new Font("Arial", UseFontSize, FontStyle.Bold);
MyRitchText.SelectionFont = VIPFont;
MyRitchText.SelectionAlignment = HorizontalAlignment.Center;
MyRitchText.SelectionColor = Color.Green;
thanks :D
Related
I am using ASP for this and I had to generate reports in PDF format and send the file back to clients so they can download it.
I made the reports using MigraDoc library and they were great but after I tried it with Arabic text I found the texts were in LTR and the characters were disjointed so I made this code to test things out
...............
MigraDoc.DocumentObjectModel.Document reportDoc = new MigraDoc.DocumentObjectModel.Document();
reportDoc.Info.Title = "test";
sec = reportDoc.AddSection();
string fileName = "test.pdf";
addformattedText(sec, "العبارة", true);
PdfDocumentRenderer renderer = new PdfDocumentRenderer(true);
renderer.Document = reportDoc;
renderer.RenderDocument();
MemoryStream pdfStream = new MemoryStream();
renderer.PdfDocument.Save(pdfStream);
byte[] bytes = pdfStream.ToArray();
...............
private void addformattedText(Section sec,string text, bool shouldBeBold = false)
{
var tf = sec.AddTextFrame();
var p = tf.AddParagraph(text);
p.Format.Font.Name = "Tahoma";
if (shouldBeBold) p.Format.Font.Bold = true;
}
I get the output like this
I have tried to encode the text and make it a unicode string using this code
private string getEscapedString(string text)
{
if (true || HasArabicCharacters(text))
{
string uString = "";
byte[] utfBytes = Encoding.Unicode.GetBytes(text);
foreach (var u in utfBytes)
{
if (u != 0)
{
uString += String.Format(#"\u{0:x4}", u);
}
}
return uString;
}
else
return text;
}
and get the returned string into a paragraph and save the PDF documents with unicode parameter set to true
But it is all the same.
I can not figure out how to get it done.
The reports were done using MigraDoc 1.50.5147 library.
The problem is Arabic language font have 4 different shap in begging,last,connected and alone, where Pdfsharp and MigraDoc can not recognize which shap to print farther more you need to reverse the character order to solve this you can use AraibcPdfUnicodeGlyphsResharper to help do such work as following:
using PdfSharp.Drawing;
using PdfSharp.Pdf;
using AraibcPdfUnicodeGlyphsResharper;
namespace MigraDocArabic
{
internal class PrintArabicUsingPdfSharp
{
public PrintArabicUsingPdfSharp(string path)
{
PdfDocument document = new PdfDocument();
document.Info.Title = "Created with PDFsharp";
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
// Create an empty page
PdfPage page = document.AddPage();
// Get an XGraphics object for drawing
XGraphics gfx = XGraphics.FromPdfPage(page);
// Create a font
XFont font = new XFont("Arial", 20, XFontStyle.BoldItalic);
var xArabicString = "كتابة اللغة العربية شيئ جميل".ArabicWithFontGlyphsToPfd();
// Draw the text
gfx.DrawString("Hello, World!", font, XBrushes.Black, new XRect(0, 0, page.Width, page.Height), XStringFormats.Center);
gfx.DrawString(xArabicString, font, XBrushes.Black, new XRect(50, 50, page.Width, page.Height), XStringFormats.Center);
// Save the document...
document.Save(path);
}
}
}
Do not Forget the Extension method
By the way this is work with iText7 too
see the image for result
Result
PDFsharp does not support RTL languages yet:
http://www.pdfsharp.net/wiki/PDFsharpFAQ.ashx#Does_PDFsharp_support_for_Arabic_Hebrew_CJK_Chinese_Japanese_Korean_6
You can work around this limitation by reversing the string.
PDFsharp does not support font ligatures yet. You are probably able to work around this limitation by replacing letters with the correct glyph (start, middle, end) depending on the position.
I am trying to build a customized PDF export form with HTML and bootstrap to use in any c# project. I want to use bootstrap designs to make my custom PDF designs. There is no problem with my own custom css file. It is working fine. But when I add the css file of bootstrap, it makes my document zoom out and be much smaller too. I cannot figure out how to fix this. I just want to create an A4 paper size form in PDF and print it.
Here is what I get when I add the bootstrap css file:
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
using iTextSharp.tool.xml.html;
using iTextSharp.tool.xml.parser;
using iTextSharp.tool.xml.pipeline.css;
using iTextSharp.tool.xml.pipeline.end;
using iTextSharp.tool.xml.pipeline.html;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows.Forms;
namespace pdf
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
byte[] result;
Document documment = new Document(PageSize.A4);
string bootstrapCssFilePath = #"C:/Users/sea_h/Desktop/cop/fulhtml/pdf/bootstrap.min.css";
string customCssFilePath = #"C:/Users/sea_h/Desktop/cop/fulhtml/pdf/custom.css";
string htmlText = #"
<html>
<head>
</head>
<body>
<div class='container'>
<col-sm4>
<h1>Deneme H1</h1>
</col-sm4>
<col-sm4>
<h2>deneme h2</h2>
</col-sm4>
<col-sm4>
<h7>deneme h7</h7>
</col-sm4>
</div>
</body>
</html>";
using (var ms=new MemoryStream())
{
PdfWriter writer = PdfWriter.GetInstance(documment, ms);
writer.CloseStream = false;
documment.Open();
HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
cssResolver.AddCssFile(bootstrapCssFilePath, true);
cssResolver.AddCssFile(customCssFilePath, true);
IPipeline pipeLine = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(documment, writer)));
XMLWorker worker = new XMLWorker(pipeLine, true);
XMLParser xmlParser = new XMLParser(worker);
xmlParser.Parse(new MemoryStream(Encoding.UTF8.GetBytes(htmlText)));
documment.Close();
result = ms.GetBuffer();
string dest = #"C:\Users\sea_h\Desktop\deneme016.pdf";
System.IO.File.WriteAllBytes(dest, result);
}
}
}
}
My custom css is:
h1{
background-color:red;
}
There is no error message.
First you need a button or something to trigger the print job, then toss on some code like this, essentially this is just going pop a print menu and go ahead with print job when user hits submit (returns 1)
In the printImage method you are going to find the declarations for fonts etc you intend to use. I'm sure there are other ways, but I use rectangles to place my draw strings where I need them. tempPoint.X and tempPoint.Y are followed by rect.location = tempPoint, this allows you to move the rectangle around as needed and keep tracking of coordinates as you go. e.graphics.drawstring() is what actually writes the text, for more specifics I would go ahead and look up some further information. From this you can just keep replicating the tempPoint movement, rect location assignment, and drawstring to customize where things are placed in your print form. As far as turning it into a pdf, windows comes with tools that are in the print menu to automate that part of it all.
private void Button1_Click(object sender, EventArgs e)
{
PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler(PrintImage);
PrintDialog printdlg = new PrintDialog();
/*preview the assigned document or you can create a different previewButton for it
printPrvDlg.Document = pd;
printPrvDlg.ShowDialog(); // this shows the preview and then show the Printer Dlg below
*/
printdlg.Document = pd;
if (printdlg.ShowDialog() == DialogResult.OK)
{
pd.Print();
}
}
void PrintImage(object o, PrintPageEventArgs e)
{
const int ORIGIN = 150;
var near = new StringFormat() { Alignment = StringAlignment.Near };
var centered = new StringFormat() { Alignment = StringAlignment.Center };
var far = new StringFormat() { Alignment = StringAlignment.Far };
Point tempPoint = new Point();
var rect = new RectangleF(0, 0, 0, 0);
var headingRect = new RectangleF(0, 0, 0, 0);
// Create font and brush.
Font titleDrawFont = new Font("Times New Roman", 16, FontStyle.Bold);
Font subtitleDrawFont = new Font("Times New Roman", 12);
Font drawFont = new Font("Times New Roman", 8);
SolidBrush drawBrush = new SolidBrush(Color.Black);
Pen blackPen = new Pen(Color.Black, 1);
// Draw string to screen.
//***************************************************************
Image logo = Image.FromFile(imageLoc);
e.Graphics.DrawImage(logo, (e.PageBounds.Width - logo.Width) / 2,
10, logo.Width, logo.Height); //Created Centered Image in original size
rect.Width = 150;
rect.Height = 20;
headingRect.Width = e.PageBounds.Width;
headingRect.Height = 40; //Set to 40 to avoid cut off with larger title text
tempPoint.X = 0;
tempPoint.Y = 110;
headingRect.Location = tempPoint;
e.Graphics.DrawString(lblTitle.Text, titleDrawFont, drawBrush, headingRect, centered);
So i just figure out why this is happenning.
Bootstrap css file using rem units for sizing.
But itextsharp using 300ppi resulotion whic means A4 paper have 2480 px X 3508 px resulotion in 300ppi.And bootstrap sizing is so small for this resulotion.
So i can modify bootstrap css file with new higher sizes as manually to fix this problem.
Or if it is possible, i can try the set itextsharp paper ppi for lower as like 70ppi.
I think there is no clear solution for this problem.
I am getting a few compile errors with my new Rectangle() - I have a windows form with a few text boxes for user input, and a button to print preview. When the button is pressed to print preview, I want the current windows form to display on the page. I am trying to code the values from the text boxes to display in the top left directly above an image that prints at the bottom half of the page. This is the syntax that I have, but I am getting multiple compile errors. What have I set-up incorrectly? I feel like writing text form a win form to a print document should be fairly straightforward, but I am failing!
private void btnPreview_Click(object sender, EventArgs e)
{
PrintPreviewDialog PrintPreviewDlg = new PrintPreviewDialog();
PrintPreviewDlg.ClientSize = new System.Drawing.Size(400, 300);
PrintPreviewDlg.Location = new System.Drawing.Point(29, 29);
PrintPreviewDlg.Name = "PrintPreviewDlg";
PrintPreviewDlg.MinimumSize = new System.Drawing.Size(375, 250);
PrintPreviewDlg.WindowState = FormWindowState.Maximized;
PrintPreviewDlg.UseAntiAlias = true;
dynamic printData = CreatePrintDocument();
printData.DefaultPageSettings.Landscape = true;
PrintPreviewDlg.Document = printData;
PrintPreviewDlg.ShowDialog();
}
printData CreatePrintDocument()
{
printData document = new printData();
document.SetParentCtrl(this);
document.PrintData.txtAssignmentName = MainInstance.txtAssignmentName.Text;
document.PrintData.txtAssignmentNumber = MainInstance.txtAssignmentNumber.Text;
document.PrintData.txtPreparedBy = MainInstance.txtPreparedBy.Text;
document.PrintData.txtAssignmentSection = MainInstance.txtAssignmentSection.Text;
document.PrintData.DocumentName = "Testing Print Functionality";
return document;
}
class printData : PrintDocument
{
Size m_SubHeaderTextFieldSize;
int m_NormalRowHeight = 0;
class DataToPrintData
{
public string txtAssignmentName, txtAssignmentNumber, txtPreparedBy, txtAssignmentSection;
}
protected override void OnPrintPage(PrintPageEventArgs e)
{
//More print specs here
int LeftSubHeadingWidth = 200;
m_SubHeaderTextFieldSize = new Size(LeftSubHeadingWidth, m_NormalRowHeight);
string printData = "Project Name: " + projectNumberTitle + System.Environment.NewLine +
"Prepared By: " + txtPreparedBy + System.Environment.NewLine +
"Assignment Section: " + txtAssignmentSection + System.Environment.NewLine;
e.Graphics.DrawString(e, new Font("Times New Roman", 12), new SolidBrush(Color.Black), new RectangleF(0,0, m_SubHeaderTextFieldSize, StringAlignment.Near);
}
}
Try this code:
var format = new StringFormat {Alignment = StringAlignment.Near};
e.Graphics.DrawString(
printData,
new Font("Times New Roman", 12),
new SolidBrush(Color.Black),
new RectangleF(new PointF(0, 0), m_SubHeaderTextFieldSize),
format);
new RectangleF(0,0, m_SubHeaderTextFieldSize, StringAlignment.Near) it looks like you are providing wrong parameters to RectangleF's constructor. There are 2 overloads - first accepts a PointF and a size you can call it like this:
new RectangleF(new PointF(0f,0f), m_SubHeaderTextFieldSize)
other one 4 points, call it like this:
new RectangleF(0f,0f, m_SubHeaderTextFieldSize.Width, m_SubHeaderTextFieldSize.Height)
any way it looks like StringAlignment.Near relates to e.Graphics.DrawString function ...
I have been trying for long but no success i have an existing pdf that i wan to load to my current C# app and want to create a simpe pusbutton to it , plaese cite some working code the default directory of the pdf is "C:\abc.pdf".
I am using itextsharp, C# VS 2010
Thanks
The closest solution I can find is something like the following.
static void AddPushbuttonField(string inputFile, iTextSharp.text.Rectangle buttonPosition, string buttonName, string outputFile)
{
using (PdfStamper stamper = new PdfStamper(new PdfReader(inputFile), File.Create(outputFile)))
{
PushbuttonField buttonField = new PushbuttonField(stamper.Writer, buttonPosition, buttonName);
stamper.AddAnnotation(buttonField.Field, 1);
stamper.Close();
}
}
This came from here, but was not ranked up as a solution. The code looks good and based on my experience with itextsharp I think this will do the trick.
Source:
Adding button in a pdf file using iTextSharp
Rectangle _rect;
_rect = new Rectangle(50, 100, 100, 100);
PushbuttonField button = new PushbuttonField(writer, _rect, "button");
PdfAnnotation widget = button.Field;
button.BackgroundColor = new GrayColor(0.75f);
button.BorderColor = GrayColor.GRAYBLACK;
button.BorderWidth = 1;
button.BorderStyle = PdfBorderDictionary.STYLE_BEVELED;
button.TextColor = GrayColor.GRAYBLACK;
button.FontSize = 11;
button.Text = "Text";
button.Layout = PushbuttonField.LAYOUT_ICON_LEFT_LABEL_RIGHT;
button.ScaleIcon = PushbuttonField.SCALE_ICON_ALWAYS;
button.ProportionalIcon = true;
button.IconHorizontalAdjustment = 0;
I am trying to set custom font to Paragraph, but I can't make it work.
I tried setting .Font= , but it only works size-wise, but it ignores font. Could you please assist?
Paragraph T = new Paragraph(newTempLine);
iTextSharp.text.Font contentFont = iTextSharp.text.FontFactory.GetFont("Webdings", 12, iTextSharp.text.Font.NORMAL);
T.Font = contentFont;
myDocument.Add(T);
Set it in the constructor:
Font contentFont = FontFactory.GetFont(…);
Paragraph para = new Paragraph(newTempLine, contentFont);
Check if below works:
string name = "Century Gothic Bold";
if (!FontFactory.IsRegistered(name))
{
string systemRoot = Environment.GetEnvironmentVariable("SystemRoot");
string path = Path.Combine(systemRoot, "fonts", #"GOTHICB.TTF");
FontFactory.Register(path);
}
var font = FontFactory.GetFont(name, fontSize, textColor);
var paragraph = new Paragraph(text, font);
Phrase phrase = new Phrase(paragraph);
var myPdfCell = new PdfPCell(phrase);