This first image shows the standard header layout when using TCPDF:
What I would like to do is right justify the text, as shown below, but I have not been able to figure out how to do this:
Please offer some suggestions! Thanks.
One way to accomplish this is with the writeHTMLCell() method. Setting the $w parameter to 0 will cause the cell to extend to the right margin. The $align parameter can then be set to 'R', which will right-align the cell content.
Example
$html = '<strong>Header Title</strong><br/>
Header string, Line 1<br/>
Header string, Line 2<br/>
Header string, Line 3';
$pdf->writeHTMLCell(
$w=0,
$h=0,
$x=0,
$y=10,
$html,
$border=0,
$ln=0,
$fill=false,
$reseth=true,
$align='R'
);
Working Example
This full example can be run in the TCPDF examples directory.
<?php
require_once('tcpdf_include.php');
class MYPDF extends TCPDF
{
public function Header()
{
$image_file = K_PATH_IMAGES.'logo_example.jpg';
$this->Image($image_file, 10, 10, 15, '', 'JPG');
$html = '<strong>Header Title</strong><br/>
Header string, Line 1<br/>
Header string, Line 2<br/>
Header string, Line 3';
$this->writeHTMLCell(
$w=0,
$h=0,
$x=0,
$y=10,
$html,
$border=0,
$ln=0,
$fill=false,
$reseth=true,
$align='R'
);
}
}
$pdf = new MYPDF();
$pdf->AddPage();
$pdf->Output('example.pdf', 'I');
Related
I encountered a problem with setting the page header text containing ampersand like ‘a&b’. The text after ‘&’ disappears in the pdf maybe because it is the reserved key in Aspose. My code looks like this:
PageSetup pageSetup = workbook.getWorksheets().get(worksheetName).getPageSetup();
//calling the function
setHeaderFooter(pageSetup, parameters, criteria)
//function for setting header and footer
def setHeaderFooter(PageSetup pageSetup, parameters, criteria = [:])
{
def selectedLoa=getSelectedLoa(parameters)
if(selectedLoa.length()>110){
String firstLine = selectedLoa.substring(0,110);
String secondLine = selectedLoa.substring(110);
if(secondLine.length()>120){
secondLine = secondLine.substring(0,122)+"...."
}
selectedLoa = firstLine+"\n"+secondLine.trim();
}
def periodInfo=getPeriodInfo(parameters, criteria)
def reportingInfo=periodInfo[0]
def comparisonInfo=periodInfo[1]
def benchmarkName=getBenchmark(parameters)
def isNonComparison = criteria.isNonComparison?
criteria.isNonComparison:false
def footerInfo="&BReporting Period:&B " + reportingInfo+"\n"
if (comparisonInfo && !isNonComparison){
footerInfo=footerInfo+"&BComparison Period:&B " +comparisonInfo+"\n"
}
if (benchmarkName){
footerInfo+="&BBenchmark:&B "+benchmarkName
}
//where I encounterd the issue,selectedLoa contains string with ampersand
pageSetup.setHeader(0, pageSetup.getHeader(0) + "\n&\"Lucida Sans,Regular\"&8&K02-074&BPopulation:&B "+selectedLoa)
//Insertion of footer
pageSetup.setFooter(0,"&\"Lucida Sans,Regular\"&8&K02-074"+footerInfo)
def downloadDate = new Date().format("MMMM dd, yyyy")
pageSetup.setFooter(2,"&\"Lucida Sans,Regular\"&8&K02-074" + downloadDate)
//Insertion of logo
try{
def bucketName = parameters.containsKey('printedRLBucketName')?parameters.get('printedRLBucketName'):null
def filePath = parameters.containsKey('printedReportLogo')?parameters.get('printedReportLogo'): null
// Declaring a byte array
byte[] binaryData
if(!filePath || filePath.contains("null") || filePath.endsWith("null")){
filePath = root+"/images/defaultExportLogo.png"
InputStream is = new FileInputStream(new File(filePath))
binaryData = is.getBytes()
}else {
AmazonS3Client s3client = amazonClientService.getAmazonS3Client()
S3Object object = s3client.getObject(bucketName, filePath)
// Getting the bytes out of input stream of S3 object
binaryData = object.getObjectContent().getBytes()
}
// Setting the logo/picture in the right section (2) of the page header
pageSetup.setHeaderPicture(2, binaryData);
// Setting the script for the logo/picture
pageSetup.setHeader(2, "&G");
// Scaling the picture to correct size
Picture pic = pageSetup.getPicture(true, 2);
pic.setLockAspectRatio(true)
pic.setRelativeToOriginalPictureSize(true)
pic.setHeight(35)
pic.setWidth(Math.abs(pic.getWidth() * (pic.getHeightScale() / 100)).intValue());
}catch (Exception e){
e.printStackTrace()
}
}
In this case, I get only ‘a’ in the pdf header all other text after ampersand gets disappeared. Please suggest me with a solution for this. I am using aspose 18.2
We have added header on a PDF page with below code snippet but we did not notice any problem when ampersand sign is included in header text.
// open document
Document document = new Document(dataDir + "input.pdf");
// create text stamp
TextStamp textStamp = new TextStamp("a&bcdefg");
// set properties of the stamp
textStamp.setTopMargin(10);
textStamp.setHorizontalAlignment(HorizontalAlignment.Center);
textStamp.setVerticalAlignment(VerticalAlignment.Top);
// set text properties
textStamp.getTextState().setFont(new FontRepository().findFont("Arial"));
textStamp.getTextState().setFontSize(14.0F);
textStamp.getTextState().setFontStyle(FontStyles.Bold);
textStamp.getTextState().setFontStyle(FontStyles.Italic);
textStamp.getTextState().setForegroundColor(Color.getGreen());
// iterate through all pages of PDF file
for (int Page_counter = 1; Page_counter <= document.getPages().size(); Page_counter++) {
// add stamp to all pages of PDF file
document.getPages().get_Item(Page_counter).addStamp(textStamp);
}
// save output document
document.save(dataDir + "TextStamp_18.8.pdf");
Please ensure using Aspose.PDF for Java 18.8 in your environment. For further information on adding page header, you may visit Add Text Stamp in the Header or Footer section.
In case you face any problem while adding header, then please share your code snippet and generated PDF document with us via Google Drive, Dropbox etc. so that we may investigate it to help you out.
PS: I work with Aspose as Developer Evangelist.
Well, yes, "&" is a reserved word when inserting headers/footers in MS Excel spreadsheet via Aspose.Cells APIs. To cope with your issue, you got to place another ampersand to paste the "& (ampersand)" in the header string. See the sample code for your reference:
e.g
Sample code:
Workbook wb = new Workbook();
Worksheet ws = wb.getWorksheets().get(0);
ws.getCells().get("A1").putValue("testin..");
String headerText="a&&bcdefg";
PageSetup pageSetup = ws.getPageSetup();
pageSetup.setHeader(0, headerText);
wb.save("f:\\files\\out1.xlsx");
wb.save("f:\\files\\out2.pdf");
Hope this helps a bit.
I am working as Support developer/ Evangelist at Aspose.
I'm using TCPDF to create PDF documents and need to render a superscript character without using HTML as the multicell option. No HTML because I need to align the words vertically at the bottom of the cell which doesn't work when the cell has HTML endabled.
Any ideas?
[Edit]
According to Jakuje's hint, I'm using this code to convert the unicode-characters:
$unicodeTable = array('<sup>1</sup>'=>'U+00B9', '<sup>2</sup>'=>'U+00B2', '<sup>3</sup>'=>'U+00B3', '<sup>4</sup>'=>'U+2074', '<sup>5</sup>'=>'U+2075');
function replace_unicode_escape_sequence($match) {
return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE');
}
function unicode_chr ($chr) {
$x = explode("+", $chr);
$str = "\u".end($x);
return preg_replace_callback('/\\\\u([0-9a-f]{4})/i', 'replace_unicode_escape_sequence', $str);
}
foreach($unicodeTable as $uKey=>$uValue){
$text = str_replace($uKey, unicode_chr($uValue), $text);
}
This works in pure php/HTML - but when I use this code with TCPDF, all I get is the unicode-code (e.g. \u00B9)
You can use UTF8 superscript, if it is some "common" letter, such as
x² or xⁿ
I found the following works with TCPDF
json_decode('"\u00B3"') // for PHP 5.x
"\u{00B2}" // for PHP 7.x
Based on this stack overflow article Unicode character in PHP string
TCPDF 6.2.13 with PHP7.1.4
With TableSorter, when I export my table in a CSV file, the accented characters doesn't appear correctly.
How to solve that ?
In version 2.16.4, the output_encoding option was added to the output widget.
The demo now has a select dropdown in which you can choose "utf8 BOM" required to make the csv file work properly in Excel.
You can set this option to include a BOM by default as follows:
output_encoding : 'data:text/csv;charset=utf8,%EF%BB%BF'
With version 2.30.6, the solution proposed above didn't work for me.
I read an article saying the unicode character \uFEFF should be specified at the beginning of the CSV data.
So, my code below insert this character only once and I reset the boolean immediately to do it only once.
Dont pay attention about scroller_* widget options if you don't use the widget 'scroller' (same for 'columnSelector' and 'filter' widgets).
Here to show UTF8 data in Excel, use the callback function output_formatContent and see my code below.
var insertBOM = true;
var $tablesorterScroll = $(".tablesorter-scroll");
$tablesorterScroll.tablesorter({
sortInitialOrder: 'desc',
widthFixed : false,
showProcessing: true,
widgets: ['filter', 'columnSelector', 'scroller', 'output'],
widgetOptions: {
// Set the max-height property of the table for the scroller widget.
scroller_height : 412, // sized with table CompanyBoard statistics (fits like that without scrollbar and finishes at the end of the row)
// Delay in milliseconds before the filter widget starts searching; This option prevents searching for
// every character while typing and should make searching large tables faster.
filter_searchDelay : 200,
// target the column selector markup
columnSelector_container : $('#columnSelector'),
// column status, true = display, false = hide
// disable = do not display on list
columnSelector_columns : {
//0: 'disable' /* set to disabled; not allowed to unselect it */
},
// remember selected columns (requires $.tablesorter.storage)
columnSelector_saveColumns: true,
// container layout
columnSelector_layout : '<label><input type="checkbox">{name}</label>',
// data attribute containing column name to use in the selector container
columnSelector_name : 'data-selector-name',
/* Responsive Media Query settings */
// enable/disable mediaquery breakpoints
columnSelector_mediaquery: false,
// toggle checkbox name
columnSelector_mediaqueryName: 'Auto: ',
// breakpoints checkbox initial setting
columnSelector_mediaqueryState: false,
// hide columnSelector false columns while in auto mode
columnSelector_mediaqueryHidden: false,
// set the maximum and/or minimum number of visible columns; use null to disable
columnSelector_maxVisible: null,
columnSelector_minVisible: null,
// responsive table hides columns with priority 1-6 at these breakpoints
// see http://view.jquerymobile.com/1.3.2/dist/demos/widgets/table-column-toggle/#Applyingapresetbreakpoint
// *** set to false to disable ***
columnSelector_breakpoints : [ '20em', '30em', '40em', '50em', '60em', '70em' ],
// data attribute containing column priority
// duplicates how jQuery mobile uses priorities:
// http://view.jquerymobile.com/1.3.2/dist/demos/widgets/table-column-toggle/
columnSelector_priority : 'data-priority',
// class name added to checked checkboxes - this fixes an issue with Chrome not updating FontAwesome
// applied icons; use this class name (input.checked) instead of input:checked
columnSelector_cssChecked : 'checked',
output_saveFileName : 'TableExport.csv',
output_separator: ';', // Excel recognize it and shows data in separated column without doing "Text to columns" Excel option.
output_replaceQuote: '\'',
output_delivery: 'd', // (p)opup, (d)ownload
output_saveRows: 'v', // (a)ll, (v)isible, (f)iltered, jQuery filter selector (string only) or filter function
output_encoding: "data:text/csv;charset=utf-8",
output_formatContent: function (config, widgetOptions, data) {
// data.isHeader (boolean) = true if processing a header cell
// data.$cell = jQuery object of the cell currently being processed
// data.content = processed cell content
// (spaces trimmed, quotes added/replaced, etc)
// **********
// use data.$cell.html() to get the original cell content
var BOM = "";
// Add BOM at file starting
if (insertBOM) {
BOM = "\uFEFF"; // set Excel enconding UTF-8
insertBOM = false;
}
return BOM + data.content.replace(/&/g, '&'); // data.content is HTML text converted so '&' has been converted to & which is the HTML reprensetation of the '&' character. Convert it back to show '&' in the CSV.
}
}
});
EDIT (15.10.2020)
My initial solution proposed above doesn't work when output_headerRows: true AND if the first header row has a rowspan. A colspan is ok.
To handle that situation, I found a way :
Before: The BOM was inserted by the function output_formatContentwhich is raised row after row (and a condition to apply the BOM only once)
Now: Use the output_callback function that is raised only once at the end of the data processed, so can insert the BOM.
IMPORTANT: You need tablesorter v2.25.1+ to be able to return data instead of true as before.
output_callback : function(config, data, url) {
BOM = "\uFEFF"; // The BOM character to force Excel opens CSV as UTF-8
return BOM + data;
}
I use Process.run where I execute an ldapsearch. Then, I get a String from stdout that look like this:
user: demo
first-name: demo
picture: trewtrewtrwrwgr
grewgrwgrwgrewgrwegrwe==
Can I do simply a Map from existing method, or I have to make one ?
Thank you.
To convert your entry :
String datas = '''user: demo
first-name: demo
picture: trewtrewtrwrwgr
grewgrwgrwgrewgrwegrwe==''';
final lines = datas.split('\n').fold([], (List<String> lines, line) {
if (line.contains(':')) lines.add(line);
// merge line that does not contain ":" with the previous
else lines.add(lines.removeLast() + '\n' + line);
return lines;
});
final m = new Map.fromIterable(lines.map((e) => e.split(':')),
key: (e) => e[0].trim(),
value: (e) => e[1].trim());
Never tried : you can also use dartdap (An LDAP Client Library for Dart).
I am new to Dart and Rikulo.
class NameView extends Section
{
View parentVu;
// the inputs
DropDownList titleDdl, suffixDdl;
TextBox firstNameTBox, middleNameTBox, lastNameTBox;
// the labels
TextView titleLbl, firstNameLbl, middleNameLbl, lastNameLbl, suffixLbl;
List<String> titles = [ 'Dr', 'Hon', 'Miss', 'Mr', 'Mrs', 'Prof', 'Sir' ];
List<String> suffixes = ['I', 'II', 'III', 'IV', 'Junior', 'Senior'];
NameView()
{
parentVu = new View()
..style.background = 'cyan'
..addToDocument();
titleLbl = new TextView( 'Title' );
parentVu.addChild( titleLbl );
titleDdl = new DropDownList( model : new DefaultListModel( titles ) )
..profile.anchorView = titleLbl
..profile.location = 'east center';
parentVu.addChild( titleDdl );
firstNameLbl = new TextView( 'First' )
..profile.anchorView = titleDdl
..profile.location = 'east center';
parentVu.addChild(firstNameLbl );
firstNameTBox = new TextBox( null, 'text' )
..profile.anchorView = firstNameLbl
..profile.location = 'east center';
//..profile.width = 'flex';
parentVu.addChild( firstNameTBox );
}
The program renders. However, it does not uses the entire width of the browser (FireFox).
I have tried for the TextBoxes
profile.width = 'flex'
but it does not work.
Any help is appreciated.
Firefox? Did you test it with Dartium? Notice that you have to compile it to JS before you can test it with browsers other than Dartium.
BTW, from your implementation, NameView seems not related to parentVu at all. If it is just a controller, it needs not to extend from Section (i.e., it doesn't have to be a view).
If a view is anchored to another, both location and size will depend on the view it anchors. In your case, if specifying flex to TextBox, its width will be the same as FirstNameLb1. It is why it is so small.
You can listen to the layout event such as:
firstNameTBox.on.layout.listen((_) {
firstNameTBox.width = parentVu.width;
});
Note: You need to do some calculation to get the right width.
See also Layout Overview