Hi,
I’m trying to create a word-like text box in a PDF document. I was able to do it in a Word file (using aspose of course), but don’t know how to do it in PDF.
This text box needs to have a small picture, a text and a hyperlink. I want to it to be like a banner in the head of the first page. No point in putting a code here, because I don’t know how to do it at all. Tried rectangles but I’m not even close.
Is it possible at all to do something like this in Aspose PDF?
Any help will be appreciated.
In the Word file, my code looks like this (this is a code that works, but I’m omiting some private stuff):
String picInBase64 = "<some base64 stuff>";
String arrowInBase64 = "<some base64 stuff>";
(I assume here that I have an open word document in the variable “doc”)
byte[] picDecoded = Base64.getDecoder().decode(picInBase64);
byte[] arrowDecoded = Base64.getDecoder().decode(arrowInBase64);
String watermarkText = "Text to put in Text Box";
DocumentBuilder builder = new DocumentBuilder(doc);
float widthInPoints = doc.getPageInfo(0).getWidthInPoints();
// the font size is proportionate to the page width,
// but should not exceed the value of 12
int fontSize = Math.min((int)Math.floor(widthInPoints / 41.0), 12);
int tabStopMultiplier = (int)Math.floor(widthInPoints / 72.0);
// create the text box and define some of its attributes
Shape textBox = new Shape(doc, ShapeType.TEXT_BOX);
textBox.setHeight(35);
textBox.setWidth(widthInPoints);
textBox.setRelativeVerticalPosition(RelativeVerticalPosition.TOP_MARGIN);
textBox.setRelativeHorizontalPosition(RelativeHorizontalPosition.PAGE);
float[] hsb = Color.RGBtoHSB(240, 240, 240, null);
textBox.setFillColor(Color.getHSBColor(hsb[0], hsb[1], hsb[2]));
textBox.getFill().setOpacity(0.5);
textBox.setStrokeColor(Color.RED);
// now we write our stuff inside the text box
textBox.appendChild(new Paragraph(doc));
builder.moveTo(textBox.getFirstParagraph());
builder.getCurrentParagraph().getParagraphFormat().setAlignment(ParagraphAlignment.LEFT);
// setPosition is a vertical attribute,
// and we want to lower the logo below sea level
builder.getFont().setPosition(-8);
ByteArrayInputStream baisLogo = new ByteArrayInputStream(logoDecoded);
builder.insertImage(baisLogo);
// after we insert the image, get the position back to 0 (at sea level)
builder.getFont().setPosition(0);
builder.getFont().setName("sans-serif");
builder.getFont().setSize(fontSize);
// left to right
builder.getFont().setBidi(false);
builder.getParagraphFormat().setBidi(false);
builder.write(" ");
builder.write(watermarkText);
// now align to the right
TabStop tab = new TabStop(tabStopMultiplier * 72, TabAlignment.RIGHT, TabLeader.NONE);
builder.getParagraphFormat().getTabStops().add(tab);
builder.write(ControlChar.TAB);
builder.getFont().setPosition(-6);
ByteArrayInputStream baisArrow = new ByteArrayInputStream(arrowDecoded);
builder.insertImage(baisArrow);
builder.getFont().setPosition(0);
builder.write(" ");
builder.getFont().setUnderline(Underline.SINGLE);
builder.getFont().setColor(Color.BLUE);
builder.insertHyperlink("Get Original", "http://www.globo.com.br/", false);
doc.getFirstSection().getBody().getFirstParagraph().appendChild(textBox);
@sharonez
To create a word-like text box in a PDF document using Aspose.PDF, you can utilize the TextBoxField
class. This allows you to add a text box that can contain text, images, and hyperlinks, similar to what you would do in a Word document. Below is a step-by-step guide along with a code example to help you achieve this.
Step-by-Step Guide
-
Set Up Your Environment: Ensure you have the Aspose.PDF library installed in your .NET project. You can install it via NuGet Package Manager with the command:
Install-Package Aspose.PDF
-
Create a New PDF Document: Start by creating a new instance of the Document
class.
-
Define the Text Box: Use the TextBoxField
class to create a text box. You will need to specify the page and the rectangle that defines the position and size of the text box.
-
Set Properties: Customize the text box by setting properties such as the border, background color, and default text.
-
Add an Image: You can insert an image into the text box using the Image
class.
-
Add a Hyperlink: Use the LinkAnnotation
class to create a hyperlink within the text box.
-
Save the Document: Finally, save the modified PDF document.
Code Example
Here’s a complete code example demonstrating how to create a text box with an image and a hyperlink:
using System.IO;
using Aspose.Pdf;
using Aspose.Pdf.Annotations;
using Aspose.Pdf.Forms;
class Program
{
static void Main()
{
// Create a new PDF document
Document pdfDocument = new Document();
// Add a page to the document
Page page = pdfDocument.Pages.Add();
// Define the rectangle for the text box
Rectangle rect = new Rectangle(100, 700, 400, 750);
// Create a text box field
TextBoxField textBoxField = new TextBoxField(page, rect);
textBoxField.PartialName = "TextBox1";
textBoxField.Value = "Your text here";
// Customize the text box
textBoxField.Border = new Border(textBoxField);
textBoxField.Border.Width = 1;
textBoxField.Color = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.LightGray);
// Add the text box to the document
pdfDocument.Form.Add(textBoxField, 1);
// Add an image (make sure to provide a valid image path)
string imagePath = "path_to_your_image.jpg";
Image image = new Image();
image.File = imagePath;
page.Paragraphs.Add(image);
// Create a hyperlink
LinkAnnotation link = new LinkAnnotation(page, new Rectangle(300, 700, 400, 720));
link.Action = new GoToURIAction("http://www.example.com");
page.Annotations.Add(link);
// Save the document
pdfDocument.Save("TextBoxExample.pdf");
}
}
Explanation of the Code
- Document Creation: A new PDF document is created, and a page is added.
- Text Box Field: A
TextBoxField
is created with specified dimensions and added to the page.
- Image Insertion: An image is added to the page. Ensure the image path is correct.
- Hyperlink: A hyperlink is created that directs to a specified URL.
- Saving the Document: The final PDF is saved with the specified filename.
This approach allows you to create a visually appealing text box in a PDF document, similar to what you would do in a Word document. You can further customize the appearance and functionality as needed.
Additional Resources
For more detailed information on working with text boxes in Aspose.PDF, you can refer to the official documentation here.
If you have any further questions or need additional assistance, feel free to ask!
It seems that the code attached here is not a Java code. Can you please supply a Java code example?
@sharonez
Can you please share the output Word document with us that you generated using the code shared in your first post? We will test the scenario in our environment and share our feedback with you accordingly.
Hi Asad,
I attach 2 word files here - Before and after.
One more thing: It turns out that when dealing with PDF files, the term “Text Box” has a different meaning than in Word files. In PDF it means a form where the user can put his text. This is not what I need, as you can see in the attached files.
Also, I need the pictures, the text and the hyperlink inside the the same rectangle, and in the same line. Just like in the attached.
Thanks a lot for your help,
Sharon
test2.docx (19.5 KB)
AsposeWatermark3 - test2.docx (18.0 KB)
@sharonez
This is how it is looking at our end.
image.png (5.5 KB)
Are you talking about the image that we highlighted in the screenshot?
Also, yes - PDF file format is entirely different format than DOC/DOCX and elements behave differently. Also, they follow different schema. Therefore, we will try to investigate whether your requirements can be achieved using Aspose.PDF or not. Please confirm against the question that we asked above.
PS: Will it suit you if you create word file as per your desire and then convert it into PDF to obtain same thing in PDF documents?
Hi Asad,
Yes, but in my word document it looks like the attached pic (I highlighted it with a blue rectangle, which in itself is not part of the word text box).
image.png (14.6 KB)
And regarding the idea of creating a new word file and converting it to PDF, well, this is the second best solution and will work for me only if the components inside the rectangle are the same as in the word (not distorted or hidden). Of course, with that kind of solution whatever I do with the document will take more time and performance-wise it’s indeed a second best solution (much slower). But if we can’t do it directly on a PDF, I can live with this solution.
Thank you for your support,
Sharon
@sharonez
Looks like your requirements can be achieved using Table in Header of the PDF Page. You can add a table with image, text as well as hyperlink inside PDF document. We believe that you can achieve it with the help of below examples in API documentation. Please feel free to let us know if you face any issues:
Hi Asad,
I appreciate your help. You put me on the right track indeed. Almost there.
One question left: how can we make the table cell background color become semi-transparent? Because, if I don’t set the background color it’s completely transparent, but if I set the background color - it’s completely opaque. And I need partial transparency.
Thank you very much for your help,
Sharon
@sharonez
This is something that we need to investigate. If possible, can you please share the code snippet that you have prepared so far? We will test the scenario in our environment and address it accordingly.
Here’s my code:
import com.aspose.pdf.*;
import java.io.ByteArrayInputStream;
import java.util.Base64;
public class PdfBanner {
static final String BANNER_TEXT = "This is a Demo - Text Within the banner.";
static final String LINK_TEXT = "Go To Site";
static final String INPUT_FILE = "PDF.pdf";
static final String OUTPUT_FILE = "PDF - output.pdf";
public static void main(String[] args) {
System.out.println("Starting");
String logoInBase64 = "iVBORw0KGgoAAAANSUhEUgAAACAAAAAmCAYAAAClI5npAAAHxUlEQVR42u2YC1BU5xXH7+6yuzx2ecpzQVhAngLLQ3kpCWCDxmAUbRKNFjVW0cZqTM1LE5qkqTFJ1U6tycRmbHzFTKuTGhXpJG3SatSM9W3TBkRUQBB0YVlYliX59cCknemYRHwwmen0znyzd+/d/c7vO4//Pd9V+I4P5X8E4MuhA2i5VP+N9+wdVt7duH5oPbB8dtHXXu/oaOOhNIX22tNDB3D80H5mlhVcd73T3sqzlcmUZiusXbdh6ADe27Ge/Jys665XVb3J1GkKZSUKk+4pHbh2+vgpPv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2v2+GtE9lsVoVCIRUOh/9J1BNABwIBXwCXl5f+dcKumNIfAANaaTy2DK2X7GbwkGGcnZ0tBXBxceHqIcytVstdMb29Qx4skr0cSOxQ9LZn0VnWO66vr1frHbvqouVyWRvgt+9WXtuyYTKZdAHI5/PrvSe28bI6PT01AK6urlzdd+evbXljZjIZ1zVc+425jdc2br25ufk/r2357qDnSPH50XfHXnyB7cW36F58le/D/yf+ABGHjoM/DixKAAAAAElFTkSuQmCC";
byte[] logoDecoded = Base64.getDecoder().decode(logoInBase64);
byte[] arrowDecoded = Base64.getDecoder().decode(arrowInBase64);
try {
Document doc = new Document(INPUT_FILE);
MarginInfo marginInfo = new MarginInfo();
marginInfo.setTop(0);
marginInfo.setLeft(0);
marginInfo.setRight(0);
marginInfo.setBottom(0);
HeaderFooter header = new HeaderFooter();
Page page = doc.getPages().get_Item(1);
page.setHeader(header);
header.getMargin().setTop(0);
header.setMargin(marginInfo);
// Initializes a new instance of the Table
Table table = new Table();
table.setDefaultCellPadding(marginInfo);
Color cellsColor = Color.fromArgb(240, 240, 240);
table.setBorder(new BorderInfo(BorderSide.Bottom, .5f, Color.getRed()));
// set the border for table cells
table.setDefaultCellBorder(new BorderInfo(BorderSide.All, .5f, cellsColor));
double pageWidth = page.getPageInfo().getWidth();
System.out.println("page width: " + pageWidth);
table.setColumnWidths("10 45 370 30 170");
Row row = table.getRows().add();
row.setFixedRowHeight(35);
// add table cells
// gap cell
Cell gapCell = row.getCells().add();
gapCell.setBackgroundColor(cellsColor);
// logo cell
Cell logoCell = row.getCells().add();
logoCell.setBackgroundColor(cellsColor);
ByteArrayInputStream baisLogo = new ByteArrayInputStream(logoDecoded);
Image logoImage = new Image();
logoImage.setImageStream(baisLogo);
logoImage.setFixWidth(25);
logoImage.setFixHeight(25);
logoCell.getParagraphs().add(logoImage);
// text cell
Cell textCell = row.getCells().add();
textCell.setBackgroundColor(cellsColor);
TextState textCellTextState = textCell.getDefaultCellTextState();
textCellTextState.setFont(FontRepository.findFont("Calibri"));
textCellTextState.setFontSize(13);
TextFragment text = new TextFragment(BANNER_TEXT);
textCell.getParagraphs().add(text);
Cell arrowCell = row.getCells().add();
arrowCell.setBackgroundColor(cellsColor);
ByteArrayInputStream baisArrow = new ByteArrayInputStream(arrowDecoded);
Image arrowImage = new Image();
arrowImage.setImageStream(baisArrow);
arrowImage.setFixWidth(23.23);
arrowImage.setFixHeight(19.41);
arrowCell.getParagraphs().add(arrowImage);
Cell hyperlinkCell = row.getCells().add();
hyperlinkCell.setBackgroundColor(cellsColor);
TextFragment hyperlink = new TextFragment(LINK_TEXT);
hyperlink.getTextState().setFont(FontRepository.findFont("Calibri"));
hyperlink.getTextState().setFontSize(12);
hyperlink.getTextState().setForegroundColor(Color.getBlue());
hyperlink.getTextState().setUnderline(true);
WebHyperlink webHyperlink = new WebHyperlink();
webHyperlink.setUrl("http://www.globo.com.br/");
hyperlink.setHyperlink(webHyperlink);
hyperlinkCell.getParagraphs().add(hyperlink);
// Add table object to first page of input document
doc.getPages().get_Item(1).getHeader().getParagraphs().add(table);
// Save updated document containing table object
doc.save(OUTPUT_FILE);
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
System.out.println("Done.");
}
}
@sharonez
We have opened the following new ticket(s) in our internal issue tracking system and will deliver their fixes according to the terms mentioned in Free Support Policies.
Issue ID(s): PDFJAVA-44934
You can obtain Paid Support Services if you need support on a priority basis, along with the direct access to our Paid Support management team.