MigraDoc and PDFsharp showing different documents when saving as PDF and image - c#

When saving, the image has the right design but the PDF has the wrong text on it. Could you explain why the documents are different?
I'm also open to other solutions for saving a PDF of the whole document and the ability to print a selected page of a multi-page document.
thanks :)
EDIT: the image is showing the date ("24th May 2016") which is correct and what I want the PDF to show, but instead the PDF is showing "TEST TEST"
1
public static void pdf() {
DateTime now = DateTime.Now;
string filename = "MixMigraDocAndPdfSharp.pdf";
filename = Guid.NewGuid().ToString("D").ToUpper() + ".pdf";
PdfDocument document = new PdfDocument();
SamplePage1(document);
document.Save(filename);
Process.Start(filename);
}
2
static void SamplePage1(PdfDocument document) {
PdfPage page = document.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(page);
gfx.MUH = PdfFontEncoding.Unicode;
gfx.MFEH = PdfFontEmbedding.Default;
XFont font = new XFont("Verdana", 13, XFontStyle.Bold);
gfx.DrawString("TEST TEST", font, XBrushes.Black,
new XRect(100, 100, page.Width - 200, 300), XStringFormats.Center);
Document doc = new Document();
Section sec = doc.AddSection();
Paragraph para = sec.AddParagraph();
header("24th May 2016");
DocumentRenderer docRenderer = new DocumentRenderer(doc);
docRenderer.PrepareDocument();
docRenderer.RenderObject(gfx, XUnit.FromCentimeter(5), XUnit.FromCentimeter(10), "12cm", para);
PageInfo info = docRenderer.FormattedDocument.GetPageInfo(1);
int dpi = 150;
int dx, dy;
if (info.Orientation == PdfSharp.PageOrientation.Portrait) {
dx = (int)(info.Width.Inch * dpi);
dy = (int)(info.Height.Inch * dpi);
} else {
dx = (int)(info.Height.Inch * dpi);
dy = (int)(info.Width.Inch * dpi);
}
Image image = new Bitmap(dx, dy, PixelFormat.Format32bppRgb);
Graphics graphics = Graphics.FromImage(image);
graphics.Clear(System.Drawing.Color.White);
float scale = dpi / 72f;
graphics.ScaleTransform(scale, scale);
gfx = XGraphics.FromGraphics(graphics, new XSize(info.Width.Point, info.Height.Point));
docRenderer.RenderPage(gfx, 1);
gfx.Dispose();
image.Save("test.png", ImageFormat.Png);
doc.BindToRenderer(docRenderer);
docRenderer.RenderObject(gfx, XUnit.FromCentimeter(5), XUnit.FromCentimeter(10), "12cm", para);
Process.Start("mspaint", "test.png");
}
3
public static void header(String date) {
Paragraph paragraph = new Paragraph();
var dateIssued = firstPage.AddTextFrame();
dateIssued.Height = "1.0cm";
dateIssued.Width = "6.0cm";
dateIssued.Left = "2.1cm";
dateIssued.RelativeHorizontal = RelativeHorizontal.Margin;
dateIssued.Top = "3.55cm";
dateIssued.RelativeVertical = RelativeVertical.Page;
paragraph = dateIssued.AddParagraph(date);
}

You call docRenderer.RenderPage(gfx, 1); for the image only. This renders the header.
You do not call docRenderer.RenderPage(gfx, 1); for the PDF. So no date there, just the "TEST TEST" you draw earlier.

Related

Create a new pdf when the page height exceeded

I'm using iTextSharp 5 to generate a clothing label as a pdf file. I need to create a second pdf rather than creating a new page if the page height is exceeded. Is it possible? How to do this? Please help.
This is my code. I needed to continue this multi language text to an another pdf if it exceeds the page height. Page length is 110 mm. Sometimes multi language text is long.
This is the generated pdf:
protected void btnOpenLabel_Click(object sender, EventArgs e)
{
//BaseFont bfTimes = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false);
//iTextSharp.text.Font titreProgFont = FontFactory.GetFont("HELVETICA", 7, Font.NORMAL,BaseColor.RED);
string fireWarning = "KEEP AWAY FROM FIRE";
string madeinText = "Made in the U.K.";
string sizeuk = "UK";
string multiLanguageText = "This is a long multi language text. This should be continue to next page if the page height exceeded. This should happen automatically when using a very long text in pdfs";
string lastLine = "Edge";
string nextpageText="This text should be placed in next page";
try
{
FileStream fs = new FileStream(Server.MapPath("pdf")+"\\"+ "MnSLabel"+".pdf",FileMode.Create);
float xpointValue = iTextSharp.text.Utilities.MillimetersToPoints(20);
float ypointvalue = iTextSharp.text.Utilities.MillimetersToPoints(110);
Rectangle pageSize = new Rectangle(xpointValue, ypointvalue);
Document document = new Document(pageSize, 0, 0, 3, 0);
PdfWriter writer = PdfWriter.GetInstance(document, fs);
document.AddAuthor("Chathu");
document.Open();
PdfContentByte cb = writer.DirectContent;
cb.BeginText();
//first text by method calling
iTextSharp.text.Font firewarningFont = FontFactory.GetFont("HELVETICA", 6, Font.NORMAL, BaseColor.RED);
Chunk c1 = new Chunk();
Phrase textPhrase = new Phrase();
ColumnText ct1 = new ColumnText(cb);
SetPDFColumnText(ct1,fireWarning,firewarningFont,c1,textPhrase,4,8,17,90,cb,5,Element.ALIGN_CENTER,Element.ALIGN_CENTER);
//end fire warning by method calling
//made in text method calling
iTextSharp.text.Font madein_textFont = FontFactory.GetFont("HELVETICA",4,Font.NORMAL,BaseColor.BLACK);
SetPDFColumnText(ct1,madeinText,madein_textFont,c1,textPhrase,2,4,18,94,cb,5,Element.ALIGN_CENTER,Element.ALIGN_CENTER);
//end made in method calling
//sizes uk
iTextSharp.text.Font sizeUKFont = FontFactory.GetFont("HELVETICA", 4, Font.NORMAL, BaseColor.BLACK);
SetPDFColumnText(ct1,sizeuk,sizeUKFont,c1,textPhrase,5,45,15,84,cb,1,Element.ALIGN_CENTER,Element.ALIGN_CENTER);
//end size uk
SetPDFColumnText(ct1, multiLanguageText , sizeUKFont, c1, textPhrase, 0, 2, 20, 1, cb, 1, Element.ALIGN_CENTER, Element.ALIGN_CENTER);
cb.EndText();
//care symbols start
PdfReader bgReader = new PdfReader(Server.MapPath("attachments") + "\\" + "CL1.pdf");
PdfImportedPage bg = writer.GetImportedPage(bgReader, 1);
float Scale = 0.25f;
cb.AddTemplate(bg, Scale, 0, 0, Scale, 2, 130);
//care symbols end
//FIBER content
document.Close();
writer.Close();
fs.Close();
lblSuccess.Text = "Sample M&S Label saved to folder";
}
catch (Exception ex)
{
lblSuccess.Text = ex.Message;
}
}
public void SetPDFColumnText(ColumnText ct, string pdfText, iTextSharp.text.Font pdfFont,Chunk pdfChunk,Phrase pdfPhrase,float lowerleft_x,float lowerleft_y,float upperright_x,float upperright_y,PdfContentByte cb,float textLeading,int lineAlignment,int textAlignment) {
float edge_lowerLeftY = 4;
float edge_upperRightY = 2;
int pdfCounter = 1;
edge_lowerLeftY = iTextSharp.text.Utilities.MillimetersToPoints(edge_lowerLeftY);
edge_upperRightY = iTextSharp.text.Utilities.MillimetersToPoints(edge_upperRightY);
//ColumnText ct1 = new ColumnText(cb);
lowerleft_x = iTextSharp.text.Utilities.MillimetersToPoints(lowerleft_x);
lowerleft_y = iTextSharp.text.Utilities.MillimetersToPoints(lowerleft_y);
upperright_x = iTextSharp.text.Utilities.MillimetersToPoints(upperright_x);
upperright_y = iTextSharp.text.Utilities.MillimetersToPoints(upperright_y);
}

Generating IDAutomationHC39M barcode is generating well but need to remove value

Hi I am using below code and the bar code is generating well but how can I remove text written down to label.
public void generateBarcode(string id)
{
int w = id.Length * 55;
Bitmap oBitmap = new Bitmap(w, 100);
Graphics oGraphics = Graphics.FromImage(oBitmap);
Font oFont = new Font("IDAutomationHC39M", 18);
PointF oPoint = new PointF(2f, 2f);
SolidBrush oBrushWrite = new SolidBrush(Color.Black);
SolidBrush oBrush = new SolidBrush(Color.White);
oGraphics.FillRectangle(oBrush, 0, 0, w, 100);
oGraphics.DrawString("*" + id + "*", oFont, oBrushWrite, oPoint);
System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image();
using (System.IO.FileStream fs = System.IO.File.Open(Server.MapPath("~/img/barcodes/") + id + ".jpg", FileMode.Create))
{
oBitmap.Save(fs, System.Drawing.Imaging.ImageFormat.Jpeg);
}
oBitmap.Dispose();
imgbarcode.ImageUrl = "~/img/barcodes/" + id + ".jpg";
}
My bar code is generating as below. Here I need to remove the bar code text as 76
According to this, the font you need to use without text is "IDAutomationC39M". Unfortunately, that's not in the free version.

ItextSharp add image on center of page with the text under it

I'm trying add picture on centre(middle) of page PDF file with text, but I can't do it right. I use for image SetAbsolutePosition, but text don't stand under picture.
I need in my Pdf file next format of page:
I use next code:
PdfWriter writer = PdfWriter.GetInstance(doc, fs);
ITextEvents ev = new ITextEvents();
writer.PageEvent = ev;
doc.Open();
var paragraph = new Paragraph();
var paragraph1 = new Paragraph();
var chunk = new Chunk("Text under picture", f14nb);
var chunk1 = new Chunk("Code of picture", f14);
img = ScaleImg(Image.GetInstance(imgNane_2));
img.SetAbsolutePosition((PageSize.A4.Width - img.ScaledWidth) / 2,
((PageSize.A4.Height - img.ScaledHeight) / 2));
paragraph.Add(img);
paragraph1.Add(chunk);
paragraph1.Add(chunk1);
doc.Add(paragraph);
doc.Add(paragraph1);
doc.Close();
private Image ScaleImg(Image img)
{
if (img.Height > img.Width)
{
//Maximum height is 800 pixels.
float percentage = 0.0f;
percentage = 640 / img.Height;
img.ScalePercent(percentage * 100);
}
else
{
//Maximum width is 600 pixels.
float percentage = 0.0f;
percentage = 500 / img.Width;
img.ScalePercent(percentage * 100);
}
return img;
}
I think, that I should use another way for solve my problem, but I don't know which.
Thank you.
I understood how do it.
This is for image with text:
public Image getWatermarkedImage(Document Doc, Image img, String watermarkText)
{
float width = img.ScaledWidth;
float height = img.ScaledHeight;
PdfTemplate template = cb.CreateTemplate(width, height);
template.AddImage(img, width, 0, 0, height, 0, 0);
ColumnText.ShowTextAligned(template, Element.ALIGN_RIGHT,
new Phrase(watermarkText, fontBold_14), width - 10, 10, 0);
return Image.GetInstance(template);
}
This is for adding text under image(main code):
var codeOfPicture = "*Code of picture* - *Код картинки*";
var chunk = new Chunk("Text under picture", font_14);
img = ScaleImg(Image.GetInstance(imgNane_1));//imgNane_2));
var tmpImg = getWatermarkedImage(doc, img, codeOfPicture);
var textY = ((PageSize.A4.Height - img.ScaledHeight) / 2) - 15;
var textX = PageSize.A4.Width / 2;
tmpImg.SetAbsolutePosition((PageSize.A4.Width - img.ScaledWidth) / 2,
((PageSize.A4.Height - img.ScaledHeight) / 2));
doc.Add(tmpImg);
ColumnText.ShowTextAligned(cb, Element.ALIGN_CENTER, new Phrase(chunk), textX, textY, 0);

iTextSharp Image minimum Table cell height

I am trying to append images to a PDF document, but the image width must = doc.PageSize.Width and height in ratio with the image width.
I am appending individual images, each in its own table and in a cell using the following method
public void AddImage(Document doc, iTextSharp.text.Image Image)
{
PdfPTable table = new PdfPTable(1);
table.WidthPercentage = 100;
table.TotalWidth = doc.PageSize.Width;
PdfPCell c = new PdfPCell(Image, true);
c.Border = PdfPCell.NO_BORDER;
c.Padding = 5;
c.FixedHeight = (doc.PageSize.Width / Image.Width) * Image.Height;
c.MinimumHeight = (doc.PageSize.Width / Image.Width) * Image.Height;
table.AddCell(c);
doc.Add(table);
}
The Document code part (Do not think this is necessary though):
using (PDFBuilder pdf = new PDFBuilder())
{
using (var doc = new Document())
{
PdfWriter writer = PdfWriter.GetInstance(doc, Response.OutputStream);
doc.Open();
var image = iTextSharp.text.Image.GetInstance(Request.MapPath("~/Images/Nemo.jpg"));
pdf.AddImage(doc, image);
pdf.AddImage(doc, image);
pdf.AddImage(doc, image);
}
}
What I want is for the images to be 100% width, and if not, the image must append on the next page.
This is currently what I am getting
And this is what I want
Any help would be greatly appreciated, thank you in advance!
Got It!
This line needed to be added:
c.Image.ScaleToFitHeight = false;
My Method
public void AddImage(Document doc, iTextSharp.text.Image Image)
{
PdfPTable table = new PdfPTable(1);
table.WidthPercentage = 100;
PdfPCell c = new PdfPCell(Image, true);
c.Border = PdfPCell.NO_BORDER;
c.Padding = 5;
c.Image.ScaleToFitHeight = false; /*The new line*/
table.AddCell(c);
doc.Add(table);
}

How do I add a link to a file in PdfSharp?

I can't seem to get PdfSharp to show a picture for this annotation. It doesn't have the PdfAnnotation.Icon property, so I can't set that.
XFont font = new XFont("Verdana", 10);
PdfPage page = wDoc.Parent.Page;
XGraphics gfx = wDoc.Parent.gfx;
XRect rec = gfx.Transformer.WorldToDefaultPage(new XRect(new XPoint(30, 60), new XSize(30, 30)));
PdfRectangle rect = new PdfRectangle(rec);
PdfLinkAnnotation link = PdfLinkAnnotation.CreateFileLink(rect, wDoc.FileLocation);
gfx.DrawString("These files were attached:", font, XBrushes.Black, 30, 50, XStringFormat.Default);
link.Rectangle = new PdfRectangle(rec);
page.Annotations.Add(link);
I've gotten it that far, and the annotation DOES exist, except it's a blank box! How do I go about making it say something, or even just show a picture?
You need to use page.AddWebLink(AREArect) and then add the text area with gfx.drawstring(AREArect)
sample code for Uri usage:
...
PdfDocument pdfDoc = PdfReader.Open(myUri.LocalPath, PdfDocumentOpenMode.Import);
PdfDocument pdfNewDoc = new PdfDocument();
for (int i = 0; i < pdfDoc.Pages.Count; i++)
{
PdfPage page = pdfNewDoc.AddPage(pdfDoc.Pages[i]);
XFont fontNormal = new XFont("Calibri", 10, XFontStyle.Regular);
XGraphics gfx = XGraphics.FromPdfPage(page);
var xrect = new XRect(240, 395, 300, 20);
var rect = gfx.Transformer.WorldToDefaultPage(xrect);
var pdfrect = new PdfRectangle(rect);
//file link
page.AddFileLink(pdfrect, myUri.LocalPath);
//web link
//page.AddWebLink(pdfrect, myUri.AbsoluteUri);
gfx.DrawString("MyFileName", fontNormal, XBrushes.Black, xrect, XStringFormats.TopLeft);
}
pdfNewDoc.Save(myDestinationUri.LocalPath + "MyNewPdfFile.pdf");
...
I am not familiar with class PdfLinkAnnotation.
You can use page.AddDocumentLink, page.AddWebLink, and page.AddFileLink to create links.
If you use these methods, you can draw the icon as an image.

Categories