Why result of GetPageLabels is different from the Adobe Acrobat - pdf

I edit page number of pdf in Adobe Acrobat X Pro.
Test PDF
result:
1-FrontCover
2-FrontFold
3-i
4-ii
5-iii
6-1
7-2
8-3
9-4
10-5
11-BackFold
12-BackCover
But this result of GetPageLabels is wrong
page number:
0-FrontCover1
1-FrontFold1
2-FrontFoldi
3-FrontFoldii
4-FrontFoldiii
5-FrontFold1
6-FrontFold2
7-FrontFold3
8-FrontFold4
9-FrontFold5
10-BackFold1
11-BackCover1
C# Code:
objLabels = PdfPageLabels.GetPageLabels(objReader);
TextBox1.Text += "page number:" + Environment.NewLine;
if (objLabels != null) {
for (i = 0; i <= objLabels.Length - 1; i++) {
TextBox1.Text += i + "-" + objLabels(i) + Environment.NewLine;
}
}
How to get the correct result like Adobe Acrobat X Pro?

There is a small bug in PdfPageLabels.GetPageLabels(PdfReader). When encountering a new page label dictionary without a P (prefix) entry, it does not reset the current prefix value:
int pagecount = 1;
String prefix = "";
char type = 'D';
for (int i = 0; i < n; i++) {
if (numberTree.ContainsKey(i)) {
PdfDictionary d = (PdfDictionary)PdfReader.GetPdfObjectRelease(numberTree[i]);
if (d.Contains(PdfName.ST)) {
pagecount = ((PdfNumber)d.Get(PdfName.ST)).IntValue;
}
else {
pagecount = 1;
}
if (d.Contains(PdfName.P)) {
prefix = ((PdfString)d.Get(PdfName.P)).ToUnicodeString();
}
if (d.Contains(PdfName.S)) {
type = ((PdfName)d.Get(PdfName.S)).ToString()[1];
}
else {
type = 'e';
}
}
...
}
You can fix this by adding the following else clause to the if in question:
if (d.Contains(PdfName.P)) {
prefix = ((PdfString)d.Get(PdfName.P)).ToUnicodeString();
}
else
{
prefix = "";
}
Whith this change I get I get
page number:
0 - FrontCover
1 - FrontFold
2 - i
3 - ii
4 - iii
5 - 1
6 - 2
7 - 3
8 - 4
9 - 5
10 - BackFold
11 - BackCover
PS: The same issue is present in the Java iText version, tested in ReadPageLabels.java.

Thank you for helping to solve my problem,
Here is my complete program.
public string[] ReadPageLabel(PdfReader objReader, int intPageCount)
{
PdfDictionary objDictionary ;
Dictionary<int, PdfObject> objTree ;
string[] arrLabels ;
int i ;
char chrLabelKind ;
string strLabelPrefix ;
int intLableNumber ;
//PdfPageLabels is wrong
//arrLabels = PdfPageLabels.GetPageLabels(objReader)
arrLabels = new string[intPageCount];
if (objReader.Catalog.Get(PdfName.PAGELABELS) != null) {
objTree = PdfNumberTree.ReadTree(PdfReader.GetPdfObjectRelease(objReader.Catalog.Get(PdfName.PAGELABELS)));
chrLabelKind = 'D';
strLabelPrefix = "";
intLableNumber = 1;
for (i = 0; i <= intPageCount - 1; i++) {
if (objTree.ContainsKey(i)) { //if reset page number
objDictionary = PdfReader.GetPdfObjectRelease(objTree[i]);
//PdfName.S:Number Kind
if (objDictionary.Contains(PdfName.S)) {
chrLabelKind = ((PdfName)objDictionary.Get(PdfName.S)).ToString()(1);
//PdfName.S:/R,/r,/A,/a,/e,/D,ToString()(1)get alphabet of Index=1
} else {
chrLabelKind = 'e';
}
//PdfName.P:Prefix
if (objDictionary.Contains(PdfName.P)) {
strLabelPrefix = ((PdfString)objDictionary.Get(PdfName.P)).ToUnicodeString();
} else {
strLabelPrefix = "";
}
//PdfName.ST:Start Number
if (objDictionary.Contains(PdfName.ST)) {
intLableNumber = ((PdfNumber)objDictionary.Get(PdfName.ST)).IntValue;
} else {
intLableNumber = 1;
}
}
switch (chrLabelKind) {
case 'R':
//I,II,III
arrLabels[i] = strLabelPrefix + factories.RomanNumberFactory.GetUpperCaseString(intLableNumber);
break;
case 'r':
//i,ii,iii
arrLabels[i] = strLabelPrefix + factories.RomanNumberFactory.GetLowerCaseString(intLableNumber);
break;
case 'A':
//A,B,C
arrLabels[i] = strLabelPrefix + factories.RomanAlphabetFactory.GetUpperCaseString(intLableNumber);
break;
case 'a':
//a,b,c
arrLabels[i] = strLabelPrefix + factories.RomanAlphabetFactory.GetLowerCaseString(intLableNumber);
break;
case 'e':
//no number kind
arrLabels[i] = strLabelPrefix;
break;
default:
//1,2,3
arrLabels[i] = strLabelPrefix + intLableNumber;
break;
}
intLableNumber += 1;
}
} else {
for (i = 0; i <= intPageCount - 1; i++) {
arrLabels[i] = i + 1;
}
}
return arrLabels;
}

Related

Execution gets stuck at date picking functionality of selenium webdriver

I am new to selenium automation, I have written a script to pick check in and check out dates from webpage of tripadvisor.in. I hope the code and xpaths are correct coz out of 7 or 8 executions the scrips successfully running only once. I thought abt synchronization issue and tried adding all types of waits but still the execution getting stuck as calendar. Sometimes stucking at check-in date, sometimes at check-out date but sometimes working fine. Can I get help to sort this issue plz...
public void selectCheckDate(String date, WebElement forwardArrow) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
try {
Date expectedDate = dateFormat.parse(prop.getProperty(date));
String day = new SimpleDateFormat("dd").format(expectedDate);
String month = new SimpleDateFormat("MMMM").format(expectedDate);
String year = new SimpleDateFormat("yyyy").format(expectedDate);
String expectedMonthYear = month + " " + year;
logger.log(Status.INFO, "Expected Month and year: "+expectedMonthYear);
WebDriverWait wait = new WebDriverWait(driver, 20);
String dd1 = "", dd2 = "";
String d1 = null, d2 = null;
boolean flag1 = false;
boolean flag2 = false;
while (true) {
String displayDate1 = driver.findElement(By.xpath("//*[#class='vr-datepicker-LargeStyles__caption--Srrff']/div")).getText();
String displayDate2 = driver.findElement(By.xpath("(//*[#class='vr-datepicker-LargeStyles__caption--Srrff']/div)[2]")).getText();
if (displayDate1.contains(expectedMonthYear)) {
//addWait();
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 7; j++) {
d1 = "//*[#id='BODY_BLOCK_JQUERY_REFLOW']/div[14]/div/div/div[2]/div/div/div[2]/div[1]/div[3]/div["
+ i + "]/div[" + j + "]";
boolean ex = isElementExists(d1);
if(ex==true) {
dd1 = driver.findElement(By.xpath(d1)).getText();
if (dd1.equals(day)) {
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(d1))).click();
//driver.findElement(By.xpath(d1)).click();
flag1 = true;
break;
}
}
}
if (flag1 == true) {
break;
}
}
if (flag1 == true) {
reportPass("Entered date: "+prop.getProperty(date));
break;
}
} else if (displayDate2.contains(expectedMonthYear)) {
//addWait();
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 7; j++) {
d2 = "//*[#id='BODY_BLOCK_JQUERY_REFLOW']/div[14]/div/div/div[2]/div/div/div[2]/div[2]/div[3]/div["
+ i + "]/div[" + j + "]";
boolean ex1 = isElementExists(d2);
if(ex1==true) {
dd2 = driver.findElement(By.xpath(d2)).getText();
if (dd2.equals(day)) {
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(d2))).click();
//driver.findElement(By.xpath(d2)).click();
flag2 = true;
break;
}
}
}
if (flag2 == true) {
break;
}
}
if (flag2 == true) {
reportPass("Entered date: "+prop.getProperty(date));
break;
}
} else {
forwardArrow.click();
}
}
} catch (ParseException e) {
reportFail(e.getMessage());
}
}

When I print array same object occurs in array please check.When I print obj then obj.dataArray contains same temp object occurs

Please check if I print obj then in data array same elements gets inserted twice instead of different. If n =2 then the first element gets pushed twice.
genLLEles(n, orgObj, homeSecObj, defaultElementObj, previousElements, socket) {
let that = this;
let arr = [];
let obj = {
dataArray: [],
socketId: socket.USER_ID,
requestId: "/sync#" + socket.id + socket.USER_ID + "#" + new Date().getTime(),
moduleName: "ORG",
action: "INSERT",
userId: socket.USER_ID
};
console.log("\n\ should be oce");
for (let i = 0; i < n; i++) { //n defines count of how many elements to be created
let temp = defaultElementObj; //selected object to insert
let _id = homeSecObj.KEY_VAL + "_TSK:" + defaultElementObj.SUB_KEY_TYPE + "_" + Date.now() + "_" + Math.floor(Math.random() * (10000 - 1)) + 1;
console.log(obj.dataArray.length);
if (obj.dataArray.length == 0) {
temp.CML_PREVIOUS_ID = previousElements.length <= 0 ? "-1" : that.getPreObj(previousElements).KEY_VAL;
temp.CML_NEXT_ID = "1";
temp.ORG_ID = orgObj.ORG_ID;
temp.DEPT_ID = orgObj.DEPT_ID;
temp.KEY_VAL = _id;
temp.CML_ID = _id;
temp.CML_REF_ID = homeSecObj.KEY_VAL;
temp.ACTIVE_STATUS = "1";
temp.CML_IMAGE_PATH = "";
temp.SYNC_PENDING_STATUS = "1";
} else {
obj.dataArray[obj.dataArray.length - 1].CML_NEXT_ID = _id;
console.log("HERE", obj.dataArray[obj.dataArray.length - 1]);
temp.CML_PREVIOUS_ID = obj.dataArray.length < 0 ? "-1" : obj.dataArray[obj.dataArray.length - 1].KEY_VAL;
temp.CML_NEXT_ID = "1";
temp.ORG_ID = orgObj.ORG_ID;
temp.DEPT_ID = orgObj.DEPT_ID;
temp.KEY_VAL = _id;
temp.CML_ID = _id;
temp.CML_REF_ID = homeSecObj.KEY_VAL;
temp.ACTIVE_STATUS = "1";
temp.CML_IMAGE_PATH = "";
temp.SYNC_PENDING_STATUS = "1";
}
obj.dataArray.push(temp);
}
console.log("\n\genLLEles ==> ", obj, "\n\n");
/*return obj;*/
}
from the above code, the values in both the if and else are coming from same parameters. So you are inserting the same values multiple times into the dataArray.

Why is my Index was out of range in MVC 4?

I've tried to create some list with increase number after some calculation each month for a year.
For example, in month 1 number = 1, month 2 number = 3, month 3 number = 5.
The calculation is like this number[i] = i + number[i - 1]. Which i is the month.
I want to show all the list like this
Month[1] = 1,
Month[2] = 3,
Month[3] = 5,
Month[4] = 7,
Month[5] = 9,
Month[6] = 11,
Month[7] = 13,
...
Month[12] = 23
Here's my Controller
for (i = 1; i <= 12; i++)
{
List<int> number = new List<int>();
if (i <= 12)
{
number[i] = a(i, number[i - 1]);
}
else
{
//something else
}
}
Here's my a function
public int a(int month, int number)
{
try
{
a = month + number;
}
catch (Exception ex)
{
throw ex;
}
return a;
}
But, when executed i'm getting this error
Index was out of range. Must be non-negative and less than the size of the collection.
I've change the controller into this
for (i = 0; i <= 12; i++)
{
//...
}
But have the same error. Can someone help me? Why I'm getting this error?
Try this
Fiddle demo
int[] number = new int[13];
for (int i = 1; i <= 12; i++)
{
if (i <= 12)
{
number[i] = a(i, number[i - 1]);
}
else
{
//something else
}
}
int j = 1;
List<int> item = new List<int>();
foreach (var a in number)
{
if (j <= 12)
{
item.Add(a);
}
else
{
break;
}
j++;
}
public int a(int month, int number)
{
int a = 0;
try
{
a = month + number;
}
catch (Exception ex)
{
throw ex;
}
return a;
}

Label Printing using iTextSharp

I have a logic to export avery label pdf. The logic exports the pdf with labels properly but when i print that pdf, the page size measurements (Page properties) that i pass isn't matching with the printed page.
Page Properties
Width="48.5" Height="25.4" HorizontalGapWidth="0" VerticalGapHeight="0" PageMarginTop="21" PageMarginBottom="21" PageMarginLeft="8" PageMarginRight="8" PageSize="A4" LabelsPerRow="4" LabelRowsPerPage="10"
The above property values are converted equivalent to point values first before applied.
Convert to point
private float mmToPoint(double mm)
{
return (float)((mm / 25.4) * 72);
}
Logic
public Stream SecLabelType(LabelProp _label)
{
List<LabelModelClass> Model = new List<LabelModelClass>();
Model = RetModel(_label);
bool IncludeLabelBorders = false;
FontFactory.RegisterDirectories();
Rectangle pageSize;
switch (_label.PageSize)
{
case "A4":
pageSize = iTextSharp.text.PageSize.A4;
break;
default:
pageSize = iTextSharp.text.PageSize.A4;
break;
}
var doc = new Document(pageSize,
_label.PageMarginLeft,
_label.PageMarginRight,
_label.PageMarginTop,
_label.PageMarginBottom);
var output = new MemoryStream();
var writer = PdfWriter.GetInstance(doc, output);
writer.CloseStream = false;
doc.Open();
var numOfCols = _label.LabelsPerRow + (_label.LabelsPerRow - 1);
var tbl = new PdfPTable(numOfCols);
var colWidths = new List<float>();
for (int i = 1; i <= numOfCols; i++)
{
if (i % 2 > 0)
{
colWidths.Add(_label.Width);
}
else
{
colWidths.Add(_label.HorizontalGapWidth);
}
}
var w = iTextSharp.text.PageSize.A4.Width - (doc.LeftMargin + doc.RightMargin);
var h = iTextSharp.text.PageSize.A4.Height - (doc.TopMargin + doc.BottomMargin);
var size = new iTextSharp.text.Rectangle(w, h);
tbl.SetWidthPercentage(colWidths.ToArray(), size);
//var val = System.IO.File.ReadLines("C:\\Users\\lenovo\\Desktop\\test stock\\testing3.txt").ToArray();
//var ItemNoArr = Model.Select(ds => ds.ItemNo).ToArray();
//string Header = Model.Select(ds => ds.Header).FirstOrDefault();
int cnt = 0;
bool b = false;
int iAddRows = 1;
for (int iRow = 0; iRow < ((Model.Count() / _label.LabelsPerRow) + iAddRows); iRow++)
{
var rowCells = new List<PdfPCell>();
for (int iCol = 1; iCol <= numOfCols; iCol++)
{
if (Model.Count() > cnt)
{
if (iCol % 2 > 0)
{
var cellContent = new Phrase();
if (((iRow + 1) >= _label.StartRow && (iCol) >= (_label.StartColumn + (_label.StartColumn - 1))) || b)
{
b = true;
try
{
var StrArr = _label.SpineLblFormat.Split('|');
foreach (var x in StrArr)
{
string Value = "";
if (x.Contains(","))
{
var StrCommaArr = x.Split(',');
foreach (var y in StrCommaArr)
{
if (y != "")
{
Value = ChunckText(cnt, Model, y, Value);
}
}
if (Value != null && Value.Replace(" ", "") != "")
{
cellContent.Add(new Paragraph(Value));
cellContent.Add(new Paragraph("\n"));
}
}
else
{
Value = ChunckText(cnt, Model, x, Value);
if (Value != null && Value.Replace(" ", "") != "")
{
cellContent.Add(new Paragraph(Value));
cellContent.Add(new Paragraph("\n"));
}
}
}
}
catch (Exception e)
{
var fontHeader1 = FontFactory.GetFont("Verdana", BaseFont.CP1250, true, 6, 0);
cellContent.Add(new Chunk("NA", fontHeader1));
}
cnt += 1;
}
else
iAddRows += 1;
var cell = new PdfPCell(cellContent);
cell.FixedHeight = _label.Height;
cell.HorizontalAlignment = Element.ALIGN_LEFT;
cell.Border = IncludeLabelBorders ? Rectangle.BOX : Rectangle.NO_BORDER;
rowCells.Add(cell);
}
else
{
var gapCell = new PdfPCell();
gapCell.FixedHeight = _label.Height;
gapCell.Border = Rectangle.NO_BORDER;
rowCells.Add(gapCell);
}
}
else
{
var gapCell = new PdfPCell();
gapCell.FixedHeight = _label.Height;
gapCell.Border = Rectangle.NO_BORDER;
rowCells.Add(gapCell);
}
}
tbl.Rows.Add(new PdfPRow(rowCells.ToArray()));
_label.LabelRowsPerPage = _label.LabelRowsPerPage == null ? 0 : _label.LabelRowsPerPage;
if ((iRow + 1) < _label.LabelRowsPerPage && _label.VerticalGapHeight > 0)
{
tbl.Rows.Add(CreateGapRow(numOfCols, _label));
}
}
doc.Add(tbl);
doc.Close();
output.Position = 0;
return output;
}
private PdfPRow CreateGapRow(int numOfCols, LabelProp _label)
{
var cells = new List<PdfPCell>();
for (int i = 0; i < numOfCols; i++)
{
var cell = new PdfPCell();
cell.FixedHeight = _label.VerticalGapHeight;
cell.Border = Rectangle.NO_BORDER;
cells.Add(cell);
}
return new PdfPRow(cells.ToArray());
}
A PDF document may have very accurate measurements, but then those measurements get screwed up because the page is scaled during the printing process. That is a common problem: different printers will use different scaling factors with different results when you print the document using different printers.
How to avoid this?
In the print dialog of Adobe Reader, you can choose how the printer should behave:
By default, the printer will try to "Fit" the content on the page, but as not every printer can physically use the full page size (due to hardware limitations), there's a high chance the printer will scale the page down if you use "Fit".
It's better to choose the option "Actual size". The downside of using this option is that some content may get lost because it's too close to the border of the page in an area that physically can't be reached by the printer, but the advantage is that the measurements will be preserved.
You can set this option programmatically in your document by telling the document it shouldn't scale:
writer.AddViewerPreference(PdfName.PRINTSCALING, PdfName.NONE);
See How to set initial view properties? for more info about viewer preferences.

OLE DB Object field to SQL image field migration c#

I am trying to migrate OLE object field (access 2003) to SQL 2005 field, now I managed to get Doc file working (function copied),
but no luck with EXCEL/PDF and other files.
short sFlag = 0;
int nIndex = 0;
int nCount = 0;
int nOffset = 0;
int nImgLen = 0;
int nReadbyte = 14400;
string szImgType = string.Empty;
if (bData.Length > 0)
{
MemoryStream memStream = new MemoryStream(bData, true);
byte[] bArray = new byte[nReadbyte];
nCount = memStream.Read(bArray, 0, nReadbyte);
if (bArray[78] == (byte)0x42 && bArray[79] == (byte)0x4D) //BMP FORMAT
{
sFlag = 1;
nOffset = 78;
szImgType = "image/bmp";
}
else
{
for (nIndex = 78; nIndex < nReadbyte - 2; nIndex++)
{
if (bArray[nIndex] == (byte)0xFF && bArray[nIndex + 1] == (byte)0xD8) //JPG FORMAT
{
sFlag = 2;
nOffset = nIndex;
szImgType = "image/pjpeg";
break;
}
else if (bArray[nIndex] == (byte)0x25 && bArray[nIndex + 1] == (byte)0x50) //PDF FORMAT
{
sFlag = 3;
nOffset = nIndex;
szImgType = "application/pdf";
FileType = "application/pdf";
break;
}
else if (bArray[nIndex] == (byte)0xD0 && bArray[nIndex + 1] == (byte)0xCF) //MSWORD FORMAT
{
sFlag = 4;
nOffset = nIndex;
szImgType = "application/msword";
FileType = "application/msword";
break;
}
}
}
if (sFlag > 0)
{
nImgLen = bData.Length - nOffset;
memStream.Position = 0;
memStream.Write(bData, nOffset, nImgLen);
memStream.Position = 0;
byte[] bImgData = bData; //new byte[nImgLen];
return bImgData;
}
else
{
return null;
}
}
else {
return null;
}
}
will like to know any pointers/ lookups to migrate ole objects to SQL 2005 fields.
-Prash