Determine the paper size of a PDF document - c#

Is there any way to the determine the paper size of a PDF document in C#. I found a dll called PdfPrintNet that will allow me to specify the paper size, but it doesn't have any methods for determining the current paper size.

PdfReader reader = new PdfReader(m);
PdfImportedPage page = writer.GetImportedPage(reader, i);
//size information
int wid=page.PageSize.Width
int heigh=page.PageSize.Height
Go through this.
Might be helpful.

If you are working with the PdfPrintNet dll, you can use PdfPrint.PaperSize Property to get the parer-size of a pdf document.
Hope it helps :)

iTextSharp should be able to help you out here.
public float GetPageHeight(string PathToPDF)
{
var reader = new PdfReader(PathToPDF);
// A post script point is 0.352777778mm
const float postScriptPoints = (float)0.352777778;
// The height is returned in post script points from iTextSharp
float height = reader.GetPageSizeWithRotation(1).Height * postScriptPoints;
reader.Close();
return height;
}
public float GetPageWidth(string PathToPDF)
{
var reader = new PdfReader(PathToPDF);
// A post script point is 0.352777778mm
const float postScriptPoints = (float)0.352777778;
// The height is returned in post script points from iTextSharp
float width = reader.GetPageSizeWithRotation(1).Width * postScriptPoints;
reader.Close();
return width;
}
Code modified from How to check a PDFs page size with iTextSharp

Related

How to add a Barcode at the top of an existing pdf using IText7 in C#?

I'm trying to use IText7 for C# in order to add a Barcode128 at the top of an existing PDF page.
Every examples I've found for the moment are adding the barcode on a new page or are done using iTextSharp or IText5.
If you have any clue of how to perform what I need, I'll be very thankful.
You have several ways to place a barcode on a PDF, as per the examples. I've converted one of the examples into C# for your convenience:
using (var document = new PdfDocument(new PdfReader(SRC), new PdfWriter(DEST)))
{
PdfCanvas canvas = new PdfCanvas(document.GetFirstPage());
Barcode128 code128 = new Barcode128(document);
code128.SetCode("12345XX789XXX");
code128.SetCodeType(Barcode128.CODE128);
PdfFormXObject xObject =
code128.CreateFormXObject(ColorConstants.BLACK, ColorConstants.BLACK, document);
float x = 36;
float y = 750;
float w = xObject.GetWidth();
float h = xObject.GetHeight();
canvas.SaveState();
canvas.SetFillColor(ColorConstants.LIGHT_GRAY);
canvas.Rectangle(x, y, w, h);
canvas.Fill();
canvas.RestoreState();
canvas.AddXObject(xObject, 36, 750);
}
it should be easy to tweak it to do what you are trying to achieve.

Merging PDFs with different orientations with iTextSharp

I have two PDF files with different orientations (first document is A4 format and the second A4 landscape).
I want to merge them but I need to preserve the original orientation of each page.
I tried with the rotation with this code:
float width = pdfImportedPage.Width;
float height = pdfImportedPage.Height;
if (width > height)
{
PdfDictionary pageDict = reader.GetPageN(documentPage);
pageDict.Put(PdfName.ROTATE, new PdfNumber(270));
}
After the rotation I call the AddPage method like this:
copy.AddPage(pdfImportedPage);
But the result is an A4 format document with the second part with the text that goes out of the page. For me is good if the text in the second part is horizontal but I need that also the orientation of the page will be as the original document (horizontal).
I'm using iTextSharp version 5.5.13.
I've just discovered that the problem was in another part of the code, after that, when I add the page number.
By the way, a good way to preserve the page orientation is to use the SetPageSize and the NewPage methods, like this piece of code:
for (int page = 1; page <= reader.NumberOfPages; page++)
{
copy.RotateContents = true;
doc.SetPageSize(reader.GetPageSizeWithRotation(page));
doc.NewPage();
importedPage = copy.GetImportedPage(reader, page);
copy.AddPage(importedPage);
}

How to convert an autocad file to a pdf file with clear view?

I'm working on an asp.net project that converts autocad file .dwg to PDF.
I use the following code to do so :
using (var image = Aspose.CAD.Image.Load(filePath))
{
// create an instance of CadRasterizationOptions & set resultant page size
var rasterizationOptions = new Aspose.CAD.ImageOptions.CadRasterizationOptions()
{
PageSize = new Aspose.CAD.SizeF(image.Size.Width, image.Size.Height),
};
// save resultant PDF
image.Save("****" + "***", new Aspose.CAD.ImageOptions.PdfOptions() { VectorRasterizationOptions = rasterizationOptions });
}
The pdf that i've got this:
another image
I want the building to be in the center of the pdf file and big enough to be useful for the user. How could i fix this view and make it clear?
I have observed the sample code shared by you. Can you please share that what issue you are having in exported PDF. Can you please share the source DWG file along with expected output PDF. Also, in your above image, the watermark on top left corner will be removed when you will set license of Aspose.CAD in your application.
I am working as Support developer/ Evangelist at Aspose.
Many Thanks
I suggest you to please try using following sample code on your end to set the print area for rendering file.
var cadImage =(CadImage) Aspose.CAD.Image.Load("filePath");
CadRasterizationOptions rasterizationOptions = new CadRasterizationOptions();
rasterizationOptions.Layouts = new string[] { "Model" };
rasterizationOptions.NoScaling = true;
// note: preserving some empty borders around part of image is the responsibility of customer
// top left point of region to draw
Point topLeft = new Point(6156, 7053);
double width = 3108;
double height = 2489;
CadVportTableObject newView = new CadVportTableObject();
newView.Name = new CadStringParameter();
newView.Name.Init("*Active");
newView.CenterPoint.X = topLeft.X + width / 2f;
newView.CenterPoint.Y = topLeft.Y - height / 2f;
newView.ViewHeight.Value = height;
newView.ViewAspectRatio.Value = width / height;
for (int i = 0; i < cadImage.ViewPorts.Count; i++)
{
CadVportTableObject currentView = (CadVportTableObject)(cadImage.ViewPorts[i]);
if (cadImage.ViewPorts.Count == 1 || string.Equals(currentView.Name.Value.ToLowerInvariant(), "*active"))
{
cadImage.ViewPorts[i] = newView;
break;
}
}
cadImage.Save("Saved.pdf", new Aspose.CAD.ImageOptions.PdfOptions() { VectorRasterizationOptions = rasterizationOptions });

Insert Element between two elements with iTextSharp

I want to add an extra Table between two tables in a pdf file.
Things to consider:
The Blue and the Red one always have a fixed height.
The Green table height between different file may change and after adding the Red element in the middle, we may need two pages.
What I know? I know how to make a table and add it to a pdf file.
My Question: Is it possible to move the Green Element and add the Red one between? How?
As you say that you know how to make a table and add it to a pdf file and that the Blue and the Red one always have a fixed height, let's assume
you have already created the table for the red part in a separate PDF,
you have determined the y coordinate at which to split the input document to insert the red part, and
you also have determined between which y coordinates in the separate PDF the table to insert is located.
Thus, the problem is reduced to
"cutting" the input document page into three stripes,
the stripe above the splitting y coordinate containing the blue box,
the stripe below the splitting y coordinate containing as much of the green box as will still fit on that page after insertion of the red box, and
the stripe at the bottom of the page containing the remainder of the green box that will overflow to a new second page,
"cutting" a stripe from the separate PDF containing the red box to insert, and
"pasting" these stripes together in the desired new order.
For this you can use a tool like this:
public class CutAndPasteTool
{
readonly Document document;
readonly PdfWriter pdfWriter;
readonly Dictionary<string, PdfTemplate> templates = new Dictionary<string, PdfTemplate>();
public CutAndPasteTool(Rectangle pageSize, Stream os)
{
document = new Document(pageSize);
pdfWriter = PdfWriter.GetInstance(document, os);
document.Open();
}
public ICutter CreateCutter(PdfReader pdfReader, int pageNumber)
{
return new SimpleCutter(pdfReader, pageNumber, pdfWriter, templates);
}
public void Paste(string name, float x, float y)
{
pdfWriter.DirectContent.AddTemplate(templates[name], x, y);
}
public void NewPage()
{
document.NewPage();
}
public void Close()
{
document.Close();
}
class SimpleCutter : ICutter
{
readonly PdfImportedPage importedPage;
readonly Dictionary<string, PdfTemplate> templates;
internal SimpleCutter(PdfReader pdfReader, int pageNumber, PdfWriter pdfWriter, Dictionary<string, PdfTemplate> templates)
{
this.importedPage = pdfWriter.GetImportedPage(pdfReader, pageNumber);
this.templates = templates;
}
public void Cut(string name, Rectangle rectangle)
{
PdfTemplate template = importedPage.CreateTemplate(rectangle.Width, rectangle.Height);
template.AddTemplate(importedPage, importedPage.BoundingBox.Left - rectangle.Left, importedPage.BoundingBox.Bottom - rectangle.Bottom);
templates.Add(name, template);
}
}
}
public interface ICutter
{
void Cut(string name, Rectangle rectangle);
}
Using this tool you can cut the stripes and paste them like this:
Rectangle pageSize = PageSize.A4; // The page size of the result file
int doc1page = 1; // The number of the page in the input PDF
float doc1split = 600; // The splitting y coordinate in the input PDF
int doc2page = 1; // The number of the page in the separate PDF
float doc2from = 700; // The top y coordinate of the table in the separate PDF
float doc2to = 600; // The bottom y coordinate of the table in the separate PDF
using (PdfReader reader1 = new PdfReader(...)) // The input PDF file
using (PdfReader reader2 = new PdfReader(...)) // The separate PDF file
using (Stream os = new FileStream(..., FileMode.Create)) // The stream to write the result to
{
Rectangle doc1box = reader1.GetPageSize(doc1page);
Rectangle doc1upper = new Rectangle(doc1box);
doc1upper.Bottom = doc1split;
Rectangle doc1lower = new Rectangle(doc1box);
doc1lower.Top = doc1split;
Rectangle doc2box = reader2.GetPageSize(doc2page);
Rectangle doc2inset = new Rectangle(doc2box);
doc2inset.Top = doc2from;
doc2inset.Bottom = doc2to;
float doc1lowerRemainHeight = pageSize.Height - doc1upper.Height - doc2inset.Height;
float doc1lowerOverflowHeight = doc1lower.Height - doc1lowerRemainHeight;
Rectangle doc1lowerRemain = new Rectangle(doc1lower);
doc1lowerRemain.Bottom = doc1lowerRemain.Top - doc1lowerRemainHeight;
Rectangle doc1lowerOverflow = new Rectangle(doc1lower);
doc1lowerOverflow.Top = doc1lowerRemain.Bottom;
CutAndPasteTool tool = new CutAndPasteTool(pageSize, os);
ICutter cutterDoc1 = tool.CreateCutter(reader1, doc1page);
cutterDoc1.Cut("Top1", doc1upper);
cutterDoc1.Cut("Bottom1Remain", doc1lowerRemain);
cutterDoc1.Cut("Bottom1Overflow", doc1lowerOverflow);
ICutter cutterDoc2 = tool.CreateCutter(reader2, doc2page);
cutterDoc2.Cut("Inset", doc2inset);
float y = pageSize.Top;
tool.Paste("Top1", 0, y-= doc1upper.Height);
tool.Paste("Inset", 0, y -= doc2inset.Height);
tool.Paste("Bottom1Remain", 0, y -= doc1lowerRemain.Height);
tool.NewPage();
y = pageSize.Top;
tool.Paste("Bottom1Overflow", 0, y -= doc1lowerOverflow.Height);
tool.Close();
}
Beware: This tool only works for content in the page content streams or content streams referenced from there, in particular not for content in annotations or XFA forms.
In case of annotations one can extend the solution to associate each annotation with one of those stripes (which might be difficult for border cases) and copy stripes and associated annotations together.
In case of XFA form tables this approach won't work unless you flatten the form first.
Furthermore, there now is some hidden text which nonetheless can be copied and pasted elsewhere. If that is not acceptable, one can replace the SimpleCutter by a more advanced ICutter implementation which removes (and not only hides) content outside of stripes, e.g. using the iText PdfCleanUpProcessor.

iText7 - How to obtain image object data

I need to add a BarcodeQRCode image to a PdfCanvas but I have not found how to do it.
I have the following code
BarcodeQRCode qr;
PdfFormXObject xObject;
Image im;
PdfCanvas canvas = new PdfCanvas(page);
qr = new BarcodeQRCode(msg);
xObject = qr.CreateFormXObject(Color.BLACK, _pdfDoc);
im = new Image(xObject);
im.SetFixedPosition(10f, 10f);
At this point I need to add the image object to the canvas, but in iText7 I need to pass the image object like a iText.IO.Image.ImageData, and that's the problem, because to make this I need the Byte[] of the image.
My question is, How to obtain the Byte[] of the Image object?
I have also tried to do this to obtain the ImageData
PdfImageXObject xoi;
xoi = new PdfImageXObject(xObject.GetPdfObject());
iText.IO.Image.ImageData id = iText.IO.Image.ImageDataFactory.Create(xoi.GetImageBytes());
but I take an error, because xoi.GetImageBytes() throws a null reference exception. Is like the PdfImageXObject is not created correctly.
I am a Little crazy and I need help, please.
Thanks.
You don't have to pass the ImageData object in iText7 in order to draw on PdfCanvas. ImageData is for common images (PNG, JPG), but for barcodes you don't want to lose quality and there are other ways of adding a barcode to the canvas.
In your case, you have already created a PdfFormXObject instance and you can add it to the canvas with PdfCanvas#addXObject as follows:
BarcodeQRCode barcode = new BarcodeQRCode(messageText);
PdfFormXObject barcodeFormXObject = barcode.createFormXObject(Color.BLACK, document);
float scale = 5;
float x = 10;
float y = 10;
canvas.addXObject(barcodeFormXObject, scale, 0, 0, scale, x, y);
UPD: In order for the barcode to be of fixed size regardless of its contents, you can use the following code:
// Tweak this value for fixed width and height
float fixedWidthAndHeight = 300;
float formXobjectWidthAndHeight = barcodeFormXObject.getHeight();
float scale = fixedWidthAndHeight / formXobjectWidthAndHeight;
float x = 10;
float y = 10;
canvas.addXObject(barcodeFormXObject, scale, 0, 0, scale, x, y);
Please note that some padding is added to the barcode, so its width/height will not be equal to fixedWidthAndHeight if you measure the distance between two opposite black squares, but it will be proportional to fixedWidthAndHeight, so you can tweak this variable as needed.

Categories