Printing Pdf using AirPrint causes cut-off content

时光总嘲笑我的痴心妄想 提交于 2019-12-04 19:26:51

As bizarre as it sounds try:

printController.showsPageRange = NO;

This seems to enable auto-scale, but sometimes prints an extra blank page at the end of the job. AirPrint is basically witchcraft.

Paresh Navadiya

You have only one option is to scale down to the ratio of the printed format from all pages of PDF then print it. I have done is got all pages of pdf into images and scaled that down to requirement :

NSString *strFilePath = [[NSBundle mainBundle] pathForResource:@"pdftouch" ofType:@"pdf"];
pic.printingItems = [[self allPagesImageFromPDF:strFilePath] copy];

Add all three methods :

Convert all PDF pages into UIImages

-(NSMutableArray *)allPagesImageFromPDF:(NSString *)strPath
{
  NSMutableArray *arrImages = [NSMutableArray array];
  CGPDFDocumentRef pdf  = CGPDFDocumentCreateWithURL((__bridge CFURLRef)[NSURL fileURLWithPath:strPath]);
  NSInteger numberOfPages = CGPDFDocumentGetNumberOfPages(pdf);
  for (NSInteger pageIndex = 1; pageIndex <= numberOfPages;
     pageIndex++)
  {
    UIImage *img = [self getThumbForPage:pdf pageIndex:pageIndex];
    [arrImages addObject:[self resizedImage:img]];
  }
  return arrImages;
}

Resize images

-(UIImage *)resizedImage:(UIImage *)image
{
  UIGraphicsBeginImageContext(CGSizeMake(612, 792)); //A4 size
  [image drawInRect:CGRectMake(0,0,612, 792)]; //A4 size
  UIImage *resizedImg = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  return resizedImg;
}

Get UIImage from CGPDFPageRef

-(UIImage *)getThumbForPage:(CGPDFDocumentRef)pdfRef pageIndex:(int)page_number{

  // Get the page
  CGPDFPageRef myPageRef = CGPDFDocumentGetPage(pdfRef, page_number);
  // Changed this line for the line above which is a generic line

  CGRect pageRect = CGPDFPageGetBoxRect(myPageRef, kCGPDFMediaBox);
  //CGFloat pdfScale = width/pageRect.size.width;
  //pageRect.size = CGSizeMake(pageRect.size.width*pdfScale, pageRect.size.height*pdfScale);
  pageRect.origin = CGPointZero;

  UIGraphicsBeginImageContext(pageRect.size);

  CGContextRef context = UIGraphicsGetCurrentContext();

  // White BG
  CGContextSetRGBFillColor(context, 1.0,1.0,1.0,1.0);
  CGContextFillRect(context,pageRect);

  CGContextSaveGState(context);

  // Next 3 lines makes the rotations so that the page look in the right direction

  CGContextTranslateCTM(context, 0.0, pageRect.size.height);
  CGContextScaleCTM(context, 1.0, -1.0);
  CGContextConcatCTM(context, CGPDFPageGetDrawingTransform(myPageRef, kCGPDFMediaBox, pageRect, 0, true));

  CGContextDrawPDFPage(context, myPageRef);
  CGContextRestoreGState(context);

  UIImage *thm = UIGraphicsGetImageFromCurrentImageContext();

  UIGraphicsEndImageContext();
  return thm;  
}

EDIT : Refer printing-uiimage-using-airprint-causes-cut-off-content

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!