ABCPdf change orientation of a specific page - c#

The code below creates a new PDF with landscape orientation. It uses ABCPdf component.
static void Main(string[] args)
{
var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "da.pdf");
var theDoc = new Doc();
//theDoc.Read(filePath);
// apply a rotation transform
theDoc.MediaBox.String = "Legal";
double w = theDoc.MediaBox.Width;
double h = theDoc.MediaBox.Height;
double l = theDoc.MediaBox.Left;
double b = theDoc.MediaBox.Bottom;
theDoc.Transform.Rotate(90, l, b);
theDoc.Transform.Translate(w, 0);
// rotate our rectangle
theDoc.Rect.Width = h;
theDoc.Rect.Height = w;
// add some text
theDoc.Rect.Inset(50, 50);
theDoc.FontSize = 96;
theDoc.AddText("Landscape Orientation");
theDoc.AddPage();
theDoc.PageNumber = theDoc.PageCount;
theDoc.AddText("Page 2");
// adjust the default rotation and save
int theID = theDoc.GetInfoInt(theDoc.Root, "Pages");
theDoc.SetInfo(theID, "/Rotate", "90");
theDoc.Save(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "out.pdf"));
theDoc.Clear();
}
Instead of creating new pdf, I would like to open an existing PDF and change the orientation of a specific page to landscape using ABCPdf. like 1st page will be in Portrait and 2nd will be on Landscape.
Thanks

You can do so, or use "AddImageDoc" method, to insert a modified page...
BUT
Abcpdf doesn't allow to overwrite the source file. From "Save Method Documentation":
ABCpdf operates an intelligent just-in-time object loading scheme
which ensures that only those objects that are required are loaded
into memory. This means that if you are modifying large documents then
server load will be kept to a minimum. The original PDF document must
be available for as long as the Doc object is being used.
As a result you cannot modify or overwrite a PDF file while it is read
into a Doc object. You will need to save your PDF to another location
and then swap the two files around after the Doc object's use of the
PDF is ended (with a call to Clear, Dispose, or Read with another PDF
file).
So you will need always a "new pdf".

Related

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 });

Resize existing image in DocX using OpenXML sdk

Got template docx with image placeholder which replaced by correct picture.
private void SetImagePartData(ImagePart imagePart, byte[] data)
{
if (imagePart != null)
{
using (var writer = new BinaryWriter(imagePart.GetStream()))
{
writer.Write(data);
}
}
}
but it preserves placeholder size. How to change it to actual image size? Byte array is aqquared from image on server, so size is known.
If you mean a content control with your placeholder you can use following code I once needed:
//Get SdtElement (can be a block, run... so I use the base class) with corresponding Tag
SdtElement block = doc.MainDocumentPart.Document.Body.Descendants<SdtElement>()
.FirstOrDefault(sdt => sdt.SdtProperties.GetFirstChild<Tag>()?.Val == contentControlTag);
//Get First drawing Element and get the original sizes of placeholder SDT
//I use SDT placeholder size as maximum size to calculate picture size with correct ratios
Drawing sdtImage = block.Descendants<Drawing>().First();
double sdtWidth = sdtImage.Inline.Extent.Cx;
double sdtHeight = sdtImage.Inline.Extent.Cy;
double sdtRatio = sdtWidth / sdtHeight;
*Calculate final width/height of image*
//Resize picture placeholder
sdtImage.Inline.Extent.Cx = finalWidth;
sdtImage.Inline.Extent.Cy = finalHeight;
//Change width/height of picture shapeproperties Transform
//This will override above height/width until you manually drag image for example
sdtImage.Inline.Graphic.GraphicData
.GetFirstChild<DocumentFormat.OpenXml.Drawing.Pictures.Picture>()
.ShapeProperties.Transform2D.Extents.Cx = finalWidth;
sdtImage.Inline.Graphic.GraphicData
.GetFirstChild<DocumentFormat.OpenXml.Drawing.Pictures.Picture>()
.ShapeProperties.Transform2D.Extents.Cy = finalHeight;
But you can use it if you are just using an image in your word document too. You just need to locate the correct Drawing element which contains the reference to your imagepart. Then you can use the bottom part of the code to adjust the image size. It's important you adjust both the Transform2D x and y as well as the Inline x and y or the image size won't be changed.

PdfSmartCopy is copying the contents at the bottom (footer) of the new PDF file

I have a function which is cropping the specific part of the pdf file and adding it into the new Pdf file but the main problem that i am getting is that it is showing the cropped part of the page into the bottom (footer) of the newly created pdf file.
Here is the code..
public static void CropPdfFile(string sourceFilePath, string outputFilePath)
{
// Allows PdfReader to read a pdf document without the owner's password
PdfReader.unethicalreading = true;
// Reads the PDF document
using (PdfReader pdfReader = new PdfReader(sourceFilePath))
{
// Set which part of the source document will be copied.
// PdfRectangel(bottom-left-x, bottom-left-y, upper-right-x, upper-right-y)
PdfRectangle rect = new PdfRectangle(0f, 9049.172f, 594.0195f, 700.3f);
using (var output = new FileStream(outputFilePath, FileMode.CreateNew, FileAccess.Write))
{
// Create a new document
using (Document doc = new Document())
{
// Make a copy of the document
PdfSmartCopy smartCopy = new PdfSmartCopy(doc, output);
// Open the newly created document
doc.Open();
// Loop through all pages of the source document
for (int i = 4; i <= pdfReader.NumberOfPages; i++)
{
// Get a page
var page = pdfReader.GetPageN(i);
// Apply the rectangle filter we created
page.Put(PdfName.CROPBOX, rect);
page.Put(PdfName.MEDIABOX, rect);
// Copy the content and insert into the new document
smartCopy.SetLinearPageMode();
var copiedPage = smartCopy.GetImportedPage(pdfReader, i);
smartCopy.AddPage(copiedPage);
}
// Close the output document
doc.Close();
}
}
}
Please help me to solve this..
The size of a PDF page (expressed in user units) depends on the value of the mediabox. For instance: The media box of an A4 page is usually defined like this [0 0 595 842]
In this case, the origin of the coordinate system (0, 0) coincides with the lower-left corner. The coordinate of the upper right corner is (595, 842).
Another possible value for an A4 page would be [0 842 595 1684]. Same width (595 user units), same height (1684 - 842 = 842 user units), but the lower-left corner now has the coordinate (0, 842) and the coordinate of the upper-right corner is (595, 1684).
You write that you create a PdfRectangle using these parameters: (bottom-left-x, bottom-left-y, upper-right-x, upper-right-y). However, you're using these hard-coded values: 0f, 9049.172f, 594.0195f, 700.3f.
Your lower-left-y (9049.172) is at a higher position than your upper-right-y (700.3). This doesn't really make sense. Hence: you should consider changing that value to something that does make sense. What value that should be, is a question only you can answer since only you know the value of the MediaBox of the file you want to crop.
In your comment, you explain that your PDF is an A4 page. You can check this by using the PdfReader method named getPageSize(). If you want to crop the page so that you only see the header of your document, you need to use something like this:
PdfRectangle rect = new PdfRectangle(0f, 842 - x, 595, 842);
Where x is the height of the header. For instance, if the header is 100 user units, then you'd need:
PdfRectangle rect = new PdfRectangle(0f, 742, 595, 842);
It is unclear why you're always talking about 100px. If you want to convert pixels to points, please read Convert Pixels to Points
Using the formula mentioned there 100 pixels equals 75 points.

Why doesn't an Image show up when I add it to a Document using iTextSharp?

Contextt: I am opening an existing, interactive PDF form containing AcroForm fields. I tried to add an image to a rectangle field in the PDF form like this:
string path = HttpContext.Current.Server.MapPath("includes");
string newFile = HttpContext.Current.Server.MapPath("Tmp") + "/completed_gray" +".pdf";
string imagepath = HttpContext.Current.Server.MapPath("Tmp");
Document doc = new Document();
try {
PdfWriter.GetInstance(doc, new FileStream(newFile, FileMode.Open));
doc.Open();
iTextSharp.text.Image gif = iTextSharp.text.Image.GetInstance(imagepath + "/CUstomRep_Eng_Col_1_V1.png");
iTextSharp.text.Rectangle rect = pdfStamper.AcroFields.GetFieldPositions("img_1_space")[0].position;
gif.ScaleAbsolute(rect.Width, rect.Height);
gif.SetAbsolutePosition(rect.Left, rect.Bottom);
doc.Add(gif);
}
catch (Exception ex) {
//Log error;
}
finally {
doc.Close();
}
The image doesn't show up in the resulting PDF.
You're creating a document using the "5 steps to create a PDF document" as documented in my books.
create a Document object.
create a PdfWriter instance.
open the document.
add content to the document.
close the document.
This contradicts with what you actually want to do: I want to add an Image in a placeholder defined by an AcroForm field.
Why are you saying you want one thing, and doing something else? Beats me. Probably because you didn't want to read the documentation.
You need something like this:
Create a PdfReader instance.
Create a PdfStamper instance.
Ask the stamper for information about the fields.
Add content to a page using the stamper instance.
Close the stamper.
In answer to your question: why doesn't my image show up in my document?
Support the coordinates of the field in the existing document are lower-left corner x = 600, y = 600 and upper-right corner x = 700, y = 700, then you are adding the image outside the visible area of the page you're creating. When you use new Document();, you're creating a document where the lower-left corner is x = 0, y = 0 and the upper-right corner is x = 595, y = 842.
In that case, you're adding the image to the document, but it's not visible because you've added it outside the rectangle that defines the page.

Categories